Swift NSEvent not working

Below is my simple AppDelegate.swift class.

// AppDelegate.swift import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { NSEvent.addGlobalMonitorForEventsMatchingMask(NSEventMask.KeyDownMask, handler: keyDown); } func keyDown(event:NSEvent!) { print("key down is \(event.keyCode)"); } } 

Why are events with keys not printed? What am I missing? I tried to search, but I can not understand.

+7
cocoa swift macos
source share
2 answers

According to NSEvent.h on addGlobalMonitorForEventsMatchingMask:handler: ::

Key-related events can only be tracked if accessibility is enabled or if your application is trusted with accessibility accessibility (see AXIsProcessTrusted in AXUIElement.h). Please note that your handler will not trigger events sent to your own application.

+7
source share

To use NSEvent globally as you currently have it, you will need to let your application trust through accessibility settings. If you want to use NSEvent locally, you can do:

 func applicationDidFinishLaunching(aNotification: NSNotification) { NSEvent.addLocalMonitorForEventsMatchingMask(NSEventMask.KeyDownMask, handler: keyDown); } func keyDown(event: NSEvent!) -> NSEvent { NSLog("key down is \(event.keyCode)"); return event } 
+7
source share

All Articles