Swift NSEvent not working

2020-06-16 09:13发布

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.

2条回答
孤傲高冷的网名
2楼-- · 2020-06-16 09:46

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
}
查看更多
够拽才男人
3楼-- · 2020-06-16 10:00

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.

查看更多
登录 后发表回答