2017-01-03 32 views
-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() 

回答

0

請問這是一個命令行應用程序?您通常只能將應用程序包(即Info.plist和應用程序標識符)註冊到全局監視器。您可能會注意到,當您運行此操作時,它會要求授權Xcode或終端,因爲這是您正在運行的應用程序。 Xcode將事件轉發給你,終端可能不會。

如果您可以將其作爲常規應用程序包(即使沒有UI),也應該沒問題。

+0

謝謝你的建議。我認爲這是通過構建沒有UI來完成我的工作的唯一方法。 – SkrewEverything