下面是我的简单AppDelegate.swift课程。
// 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)");
}
}为什么没有打印按键事件?我遗漏了什么?我试过到处找,但搞不清楚。
发布于 2015-12-12 21:29:21
根据NSEvent.h on addGlobalMonitorForEventsMatchingMask:handler:
只有在启用可访问性或信任应用程序进行可访问性访问(请参阅AXUIElement.h中的AXIsProcessTrusted )时,才可能监视与密钥相关的事件。请注意,对于发送到您自己的应用程序的事件,您的处理程序不会被调用。
发布于 2015-12-12 21:31:44
为了像现在这样在全局上使用NSEvent,您必须允许通过可访问性设置信任您的应用程序。如果您想在本地使用NSEvent,可以这样做:
func applicationDidFinishLaunching(aNotification: NSNotification) {
NSEvent.addLocalMonitorForEventsMatchingMask(NSEventMask.KeyDownMask, handler: keyDown);
}
func keyDown(event: NSEvent!) -> NSEvent {
NSLog("key down is \(event.keyCode)");
return event
}https://stackoverflow.com/questions/34244865
复制相似问题