Csaba Okrona Csaba Okrona - 1 year ago 364
Swift Question

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

I'm trying to have a handler in my Mac OS X app written in Swift for a global (system-wide) hotkey combo but I just cannot find proper documentation for it. I've read that I'd have to mess around in some legacy Carbon API for it, is there no better way? Can you show me some proof of concept Swift code? Thanks in advance!

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download