-1
我從互聯網上搜集了一些用於監視全局關鍵事件的代碼。運行可執行文件時沒有記錄的按鍵事件
它運行正常,當我通過Xcode運行它。問題是當我通過終端運行它時,它不捕獲任何事件。我已在Xcode和終端的設置中啓用了輔助功能。
下面是代碼:
func handlerEvent(aEvent: (NSEvent!)) -> Void {
let stringBuilder = aEvent.characters!
print(stringBuilder, separator: "", terminator: "")
}
// MARK: Event Monitor
func listenForEvents() {
let mask = (NSEventMask.keyDown)
_ = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: handlerEvent)
}
func acquirePrivileges() -> Bool {
let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String : true]
let accessEnabled = AXIsProcessTrustedWithOptions(options)
if !accessEnabled {
print("Access Denied")
}
return accessEnabled
}
class ApplicationDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
if acquirePrivileges()
{
print("Access Granted")
}
print("Starting logging")
listenForEvents()
}
}
let application = NSApplication.shared()
let applicationDelegate = ApplicationDelegate()
application.delegate = applicationDelegate
application.activate(ignoringOtherApps: true)
application.run()
謝謝你的建議。我認爲這是通過構建沒有UI來完成我的工作的唯一方法。 – SkrewEverything