How to listen to global hotkeys with Swift in an OS X app? How to listen to global hotkeys with Swift in an OS X app? swift swift

How to listen to global hotkeys with Swift in an OS X app?


Since Swift 2.0, you can now pass a function pointer to C APIs.

var gMyHotKeyID = EventHotKeyID()gMyHotKeyID.signature = OSType("swat".fourCharCodeValue)gMyHotKeyID.id = UInt32(keyCode)var eventType = EventTypeSpec()eventType.eventClass = OSType(kEventClassKeyboard)eventType.eventKind = OSType(kEventHotKeyPressed)// Install handler.InstallEventHandler(GetApplicationEventTarget(), {(nextHanlder, theEvent, userData) -> OSStatus in    var hkCom = EventHotKeyID()    GetEventParameter(theEvent, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID), nil, sizeof(EventHotKeyID), nil, &hkCom)    // Check that hkCom in indeed your hotkey ID and handle it.}, 1, &eventType, nil, nil)// Register hotkey.let status = RegisterEventHotKey(UInt32(keyCode), UInt32(modifierKeys), gMyHotKeyID, GetApplicationEventTarget(), 0, &hotKeyRef)


I don't believe you can do this in 100% Swift today. You'll need to call InstallEventHandler() or CGEventTapCreate(), and both of those require a CFunctionPointer, which can't be created in Swift. Your best plan is to use established ObjC solutions such as DDHotKey and bridge to Swift.

You can try using NSEvent.addGlobalMonitorForEventsMatchingMask(handler:), but that only makes copies of events. You can't consume them. That means the hotkey will also be passed along to the currently active app, which can cause problems. Here's an example, but I recommend the ObjC approach; it's almost certainly going to work better.

let keycode = UInt16(kVK_ANSI_X)let keymask: NSEventModifierFlags = .CommandKeyMask | .AlternateKeyMask | .ControlKeyMaskfunc handler(event: NSEvent!) {    if event.keyCode == self.keycode &&        event.modifierFlags & self.keymask == self.keymask {            println("PRESSED")    }}// ... to set it up ...    let options = NSDictionary(object: kCFBooleanTrue, forKey: kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString) as CFDictionaryRef    let trusted = AXIsProcessTrustedWithOptions(options)    if (trusted) {        NSEvent.addGlobalMonitorForEventsMatchingMask(.KeyDownMask, handler: self.handler)    }

This also requires that accessibility services be approved for this app. It also doesn't capture events that are sent to your own application, so you have to either capture them with your responder chain, our use addLocalMointorForEventsMatchingMask(handler:) to add a local handler.


A quick Swift 3 update for the setup:

let opts = NSDictionary(object: kCFBooleanTrue, forKey: kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString) as CFDictionaryguard AXIsProcessTrustedWithOptions(opts) == true else { return }NSEvent.addGlobalMonitorForEvents(matching: .keyDown, handler: self.handler)