user3803526 user3803526 - 1 year ago 121
Swift Question

Capture Global Keydown Events (not simply observe)

I've created some global hotkeys. However using

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
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download