Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift NSEvent not working

Tags:

macos

swift

cocoa

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.

like image 722
user3813948 Avatar asked Dec 12 '15 20:12

user3813948


2 Answers

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
}
like image 102
l'L'l Avatar answered Oct 05 '22 09:10

l'L'l


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.

like image 28
Tamás Zahola Avatar answered Oct 05 '22 11:10

Tamás Zahola