Home > Blockchain >  Listen to keypress across all windows in Swift
Listen to keypress across all windows in Swift

Time:02-05

How can I listen to NSEvents while my app has the focus, but independently of which window is active?

I'm not looking to listen to system-wide events, I only want to listen to single and/or modified keystrokes while my app has the focus, but all examples I could find, listen NSEvents from NSWindow or NSView.

My app has multiple windows and I want to catch all keystrokes while any of those windows are focused.

CodePudding user response:

Override NSApplication.sendEvent. This is the central dispatching method for all events in the application. You can determine which events you care about, and either consume them, or send them along using super. This is a documented override point in NSApplication. It is not a hack.

Note that this requires subclassing NSApplication itself. It's not handled by the application delegate. For instructions on subclassing NSApplication in Swift, see Subclass NSApplication in Swift. (Read all the comments; the answer is a little messy. The key is setting NSPrincipalClass.)

For more technical details, see the Cocoa Event Handling Guide, which covers the whole architecture.

CodePudding user response:

It looks like the NSEvent.addLocalMonitorForEvents(matching:handler:) API is exactly what you're looking for.

  • Related