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

前端 未结 6 1765
北荒
北荒 2020-12-12 17:08

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

6条回答
  •  被撕碎了的回忆
    2020-12-12 17:41

    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)
    

提交回复
热议问题