2

I want to trigger a function when a Window focus is changed

How can I add an observer based on kAXFocusedWindowChangedNotification

I am trying to use like this:

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")
         }
      }
}

so, why the func callback is not has being triggered when I change window focus of safari?

a_kira
  • 195
  • 10

1 Answers1

1

As @Willeke has already pointed out, you need to keep a reference to observer (probably you want to make it a property).

For others who are interested, also take a look at this answer here https://stackoverflow.com/a/33262376/1531256 explaining how to pass self to the callback C-function.

codingFriend1
  • 6,487
  • 6
  • 45
  • 67