我想在窗口焦点更改时触发函数
如何基于kAXFocusedWindowChangedNotification添加观察者
我试着这样使用:
override func viewDidLoad() {
super.viewDidLoad()
var observer: AXObserver? = nil
let pid_app: pid_t = NSWorkspace.shared.runningApplications.first(where: {$0.localizedName == "Safari"})!.processIdentifier as pid_t
let app_ref = AXUIElementCreateApplication(pid_app)
func callBack(observer: AXObserver?, element: AXUIElement?, notification: CFString, refcon: UnsafeMutableRawPointer?) {print("Fired!")}
if AXObserverCreate(pid_app, callBack, &observer) == .success {
print("AXObserverCreate success!")
if AXObserverAddNotification(observer!, app_ref, kAXFocusedWindowChangedNotification as CFString, UnsafeMutableRawPointer(Unmanaged.passRetained(self).toOpaque())) == .success {
print("AXObserverAddNotification success!")
CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(observer!), .defaultMode)
print("Watching")
}
}
}
那么,为什么当我改变safari的窗口焦点时没有触发func回调呢?
1条答案
按热度按时间lf5gs5x21#
正如@Willeke已经指出的,您需要保留对
observer
的引用(可能您希望将其作为属性)。对于其他感兴趣的人,也可以看看https://stackoverflow.com/a/33262376/1531256的答案,它解释了如何将
self
传递给回调C函数。