Swift中的全局修改键按键检测
我正在尝试使用Carbon的函数RegisterEventHotKey来创建按下命令键时的热键.我这样使用它:
InstallEventHandler(GetApplicationEventTarget(),handler,1,&eventType,nil,nil) RegisterEventHotKey(UInt32(cmdKey),hotKeyID,GetApplicationEventTarget(),&hotKeyRef) 但是,当我只使用命令键时,它不会调用处理程序.如果我将cmdKey替换为任何其他非修饰符键代码,则调用该处理程序. 有没有人有任何建议允许应用程序在按下命令键时全局识别?谢谢. 解决方法
您可以将与事件匹配.flagsChanged的全局监视器添加到视图控制器,以便您可以检查其modifierFlags与deviceIndependentFlagsMask的交集并检查生成的键.
class func addGlobalMonitorForEvents(matching mask: NSEventMask,handler block: @escaping (NSEvent) -> Void) -> Any?
import Cocoa class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged) { switch $0.modifierFlags.intersection(.deviceIndependentFlagsMask) { case [.shift]: print("shift key is pressed") case [.control]: print("control key is pressed") case [.option] : print("option key is pressed") case [.command]: print("Command key is pressed") case [.control,.shift]: print("control-shift keys are pressed") case [.option,.shift]: print("option-shift keys are pressed") case [.command,.shift]: print("command-shift keys are pressed") case [.control,.option]: print("control-option keys are pressed") case [.control,.command]: print("control-command keys are pressed") case [.option,.command]: print("option-command keys are pressed") case [.shift,.control,.option]: print("shift-control-option keys are pressed") case [.shift,.command]: print("shift-control-command keys are pressed") case [.control,.option,.command]: print("control-option-command keys are pressed") case [.shift,.command,.option]: print("shift-command-option keys are pressed") case [.shift,.command]: print("shift-control-option-command keys are pressed") default: print("no modifier keys are pressed") } } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |