我想在窗口焦点改变时触发一个函数
如何添加基于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的窗口焦点?
正如@Willeke已经指出的,您需要保持对observer
的引用(可能您想使其成为属性)。
对于其他感兴趣的人,也可以看看这里的答案https://stackoverflow.com/a/33262376/1531256,它解释了如何将self
传递给回调c函数。