Swift 中的全局修改键检测

Global modifier key press detection in Swift

我正在尝试使用 Carbon 的函数 RegisterEventHotKey 为按下命令键时创建一个热键。我是这样使用它的:

InstallEventHandler(GetApplicationEventTarget(), handler, 1, &eventType, nil, nil)
RegisterEventHotKey(UInt32(cmdKey), 0, hotKeyID, GetApplicationEventTarget(), 0, &hotKeyRef)

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

有没有人有任何建议可以让应用程序在按下命令键时全局识别?谢谢。

您可以将 Global Monitor For Events 匹配 .flagsChanged 添加到您的视图控制器,这样您就可以检查它的 modifierFlags 与 deviceIndependentFlagsMask 的交集并检查生成的键。

Declaration

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

installs an event monitor that receives copies of events posted to other applications. Events are delivered asynchronously to your app and you can only observe the event; you cannot modify or otherwise prevent the event from being delivered to its original target application. Key-related events may only be monitored if accessibility is enabled or if your application is trusted for accessibility access (). Note that your handler will not be called for events that are sent to your own application.

import Cocoa
class ViewController: NSViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged) {
            switch [=11=].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")
            }
        }
    }
}