小编典典

如何在OS X应用程序中使用Swift监听全局热键?

swift

我试图在我的Mac OS
X应用程序中使用处理程序以Swift编写一个全局(系统级)热键组合,但我只是找不到适合的文档。我已经读到我必须弄乱一些旧版Carbon
API,有没有更好的方法?您能告诉我一些概念证明Swift代码吗?提前致谢!


阅读 248

收藏
2020-07-07

共1个答案

小编典典

从Swift 2.0开始,您现在可以将函数指针传递给C API。

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)
2020-07-07