如何在MacOS应用程序中使用SWIFT收听全球热键? [英] How to listen to global hotkeys with Swift in a macOS app?

查看:70
本文介绍了如何在MacOS应用程序中使用SWIFT收听全球热键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试在我的Mac OS X应用程序中为全局(系统范围)热键组合使用SWIFT编写的处理程序,但我就是找不到合适的文档。我读到我必须为它在一些遗留的Carbon API中乱搞,没有更好的方法了吗?你能给我看一些SWIFT代码的概念证明吗?提前感谢!

推荐答案

从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)

这篇关于如何在MacOS应用程序中使用SWIFT收听全球热键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆