Wanting to monitor NSEvents globally in a command line app (written in Swift) I stumbled upon this thread. I also expected RunLoop.main.run() to keep the app running and help the observer receive events, but it didn't work. No errors, but also no events received in the handler.
With the pointers from Quinn here and some more reading about how an AppKit app launched I realised there also is the NSApplication.shared.run() method to start the runloop for a NSApplication. That worked out!
So the following code is a minimal sample for a working command line app that is monitoring events:
import AppKit
@main
public struct CLIapp {
public static func main() {
NSEvent.addGlobalMonitorForEvents(matching: .any) { event in print("Event received") }
NSApplication.shared.run() // This keeps the app running & makes sure events are received
}
}
Topic:
UI Frameworks
SubTopic:
AppKit
Tags: