Quinn’s sample works perfectly for capturing key up/down events. Thanks for that!
I need to get the characters associated with key-up or key-down events. Using the NSEvent’s characters property, I wrote this in the didReceiveEvent callback:
let nsEvent = NSEvent(cgEvent: event)
print("Characters: \(event.characters)")
However, this crashes in a SwiftUI or AppKit app with a failing assertion in isIGetInputSourceRef while processing the raw key code.
Running event.characters on the main thread seems to be a workaround. There’s no documentation suggesting this, and the CGEvent comes in on a background thread through the tap. Other CGEvent and NSEvent properties work fine from any thread.
Is it expected that event.characters must be called from the main thread? Is it safe to dispatch it to the main queue, or could it fail if the main queue is handling other events? What’s the recommended approach?
Additionally, in my command-line executable without a UI, accessing characters from a background thread works fine. Why does this fail in a UI app? Is accessing it on the main thread a requirement?
It would be very valuable if someone could shed some light on this.