gcstr
gcstr

Reputation: 1547

Listen to keypress across all windows in Swift

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.

Upvotes: 2

Views: 126

Answers (2)

Rob Napier
Rob Napier

Reputation: 299565

This will work, but it's overkill for this problem. See Alexander's answer for the correct approach.


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.

Upvotes: 3

Alexander
Alexander

Reputation: 63369

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

Upvotes: 2

Related Questions