我正在尝试监听全局键盘事件,并让我的应用程序在检测到某些按键时执行特定的操作。为此,我想使用:
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Add keyboard event listener.
NSEvent.addGlobalMonitorForEvents(matching: .keyDown, handler:
{
print("key down!");
print($0.keyCode);
});
}
}
Run Code Online (Sandbox Code Playgroud)
我正在以这种方式检查 appDelegate.swift 中的可访问权限:
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
//check if the process is trusted for accessibility. This is important for us to listen for keyboard events system wide.
let checkOptPrompt = kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString
let options = [checkOptPrompt: true]
let isAppTrusted = AXIsProcessTrustedWithOptions(options as CFDictionary?);
if(isAppTrusted != true) …Run Code Online (Sandbox Code Playgroud)