user3803526 user3803526 - 23 days ago 11
Swift Question

Capture Global Keydown Events (not simply observe)

I've created some global hotkeys. However using

addGlobalMonitorForEventsMatchingMask
I can only observe keydown events. What if I want to capture the event and prevent other applications from receiving it?

Here's what I have for observing keydown events:

class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
NSEvent.addGlobalMonitorForEventsMatchingMask(.KeyDownMask, handler: keyDown)
NSEvent.addLocalMonitorForEventsMatchingMask(.KeyDownMask) { (event) -> NSEvent! in
self.keyDown(event)
return event
}
}
func keyDown(event : NSEvent) {
if event.modifierFlags.contains(.ControlKeyMask) && event.modifierFlags.contains(.AlternateKeyMask) && event.modifierFlags.contains(.CommandKeyMask) && event.keyCode == 126 {
print("⌃⌥⌘↑ pressed")
}
}
}


I'm not sure where to start to capture keydown events. Any help would be great. Thanks.

Answer

DDHotKey allows you to capture keydown events and use them to trigger function in you app. I discovered it recently in this post. If you don't already know how to integrate Objective-C code into a Swift project, you can find the Apple documentation here.