Swift中的全局修改键按键检测

use*_*395 8 macos macos-carbon swift

我正在尝试使用Carbon的功能RegisterEventHotKey来创建按下命令键时的热键.我这样使用它:

InstallEventHandler(GetApplicationEventTarget(), handler, 1, &eventType, nil, nil)
RegisterEventHotKey(UInt32(cmdKey), 0, hotKeyID, GetApplicationEventTarget(), 0, &hotKeyRef)
Run Code Online (Sandbox Code Playgroud)

但是,handler当我只使用命令键时它不会调用.如果我替换cmdKey为任何其他非修饰符键代码,则调用该处理程序.

有没有人有任何建议允许应用程序在按下命令键时全局识别?谢谢.

Leo*_*bus 10

您可以添加与.flagsChanged视图控制器匹配的事件的全局监视器,以便您可以检查其modifierFlags与deviceIndependentFlagsMask的交集,并检查生成的键.

宣言

class func addGlobalMonitorForEvents(matching mask: NSEventMask, handler block: @escaping (NSEvent) -> Void) -> Any?
Run Code Online (Sandbox Code Playgroud)

安装一个事件监视器,接收发布到其他应用程序的事件副本.事件以异步方式发送到您的应用程序,您只能观察事件; 您无法修改或以其他方式阻止将事件传递到其原始目标应用程序.如果启用了辅助功能,或者您的应用程序受信任以进行辅助功能访问,则只能监视与密钥相关的事件(请参阅AXIsProcessTrusted()).请注意,不会为发送到您自己的应用程序的事件调用您的处理程序.

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")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)