问题描述
我正在尝试使用Carbon的功能RegisterEventHotKey
为按下命令键时创建一个热键.我这样使用它:
I'm trying to use Carbon's function RegisterEventHotKey
to create a hotkey for when the command key is pressed. I'm using it like so:
InstallEventHandler(GetApplicationEventTarget(), handler, 1, &eventType, nil, nil)
RegisterEventHotKey(UInt32(cmdKey), 0, hotKeyID, GetApplicationEventTarget(), 0, &hotKeyRef)
但是,当我仅使用命令键时,它不会调用handler
.如果我将cmdKey
替换为任何其他非修饰键代码,则会调用该处理程序.
However, it doesn't call handler
when I only use the command key. The handler is called if I replace cmdKey
with any other non-modifier key code.
是否有人有任何建议可让应用程序在按下命令键时全局识别?谢谢.
Does anyone have any suggestions that would allow the app to globally recognize when the command key is pressed? Thanks.
推荐答案
您可以将与.flagsChanged
匹配的全局事件监控器添加到视图控制器,以便您可以检查它与deviceIndependentFlagsMask的ModifyFlags交集并检查生成的键.
You can add Global Monitor For Events matching .flagsChanged
to your view controller so you can check its modifierFlags intersection with deviceIndependentFlagsMask and check the resulting keys.
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, .control, .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, .control, .option, .command]:
print("shift-control-option-command keys are pressed")
default:
print("no modifier keys are pressed")
}
}
}
}
这篇关于Swift中的全局修改器按键检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!