您可以添加事件匹配的全局监视器.flagsChanged
到你的视图控制器,这样你就可以检查它的modifierFlags与deviceIndependentFlagsMask的交集并检查结果键。
宣言
class func addGlobalMonitorForEvents(matching mask: NSEventMask, handler block: @escaping (NSEvent) -> Void) -> Any?
安装一个事件监视器,用于接收发布到的事件副本
其他应用程序。事件异步传送到您的应用程序
并且您只能观察事件;您不能修改或以其他方式
阻止事件传递到其原始目标
应用。仅当可访问性时才可以监视与按键相关的事件
已启用,或者您的应用程序是否受信任可访问
(请参阅 AXIsProcessTrusted() https://stackoverflow.com/a/58405058/2303865)。请注意,您的处理程序不会被调用
对于发送到您自己的应用程序的事件。
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")
}
}
}
}