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)");
}
}
How come key down events are not being printed? What am I missing? I've tried searching around but can't figure it out.
In order to use NSEvent
globally as you currently have it you would have to allow your application to be trusted through accessibility settings. If you want to use NSEvent
locally you could do:
func applicationDidFinishLaunching(aNotification: NSNotification) {
NSEvent.addLocalMonitorForEventsMatchingMask(NSEventMask.KeyDownMask, handler: keyDown);
}
func keyDown(event: NSEvent!) -> NSEvent {
NSLog("key down is \(event.keyCode)");
return event
}
According to NSEvent.h
on addGlobalMonitorForEventsMatchingMask:handler:
:
Key-related events may only be monitored if accessibility is enabled or if your application is trusted for accessibility access (see AXIsProcessTrusted in AXUIElement.h). Note that your handler will not be called for events that are sent to your own application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With