I would like to be notified when the main window of the frontmost app changes i.e changing a tab in a browser, changing a document in SublimeText etc. and get the title of that current main window. I'm quite new to Swift so I'd appreciate any kind of info/help.
I've written a piece of code to observe the frontmostapp by using addobserver on the didActivateAppNotification object. It successfully prints out the frontmost app everytime it changes to a new one.
So I also wanna do the same with main window of the frontmost app. However, all I can do is to get the window lists of the frontmost app via CGWindowListOption as explained here, then scroll through it to get a list of the windows of frontmost app and filter it to get the mainwindow. But I don't want a polling solution, which is to get this list every second. Instead I'd like to get use of a notification observer so that I can actually ask when the mainwindow changes. -I've also tried some Applescript solutions, they all need to be polling solutions.
I couldn't find any tutorials, examples of NSAccessibilityNotificationName classes as it says they require special handling in Apple Dev Forums. How could I observe those notifications for external applications? (specifically mainWindowChanged in my example)
Cheers, happy coding!
class activeApp: NSObject {
override init() {
super.init()
NSWorkspace.shared.notificationCenter.addObserver(self,
selector: #selector(printMe(notification:)),
name: NSWorkspace.didActivateApplicationNotification,
object:nil)
}
@objc func printMe(notification: NSNotification) {
let app = notification.userInfo!["NSWorkspaceApplicationKey"] as! NSRunningApplication
print(app.localizedName!)
}
}
let runme = activeApp()
RunLoop.main.run()