swift NSEvent 不工作

标签 swift macos cocoa

下面是我的简单 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)");
    }

}

为什么按键按下事件没有被打印出来?我错过了什么? 我试过四处搜索,但无法弄清楚。

最佳答案

根据 addGlobalMonitorForEventsMatchingMask:handler: 上的 NSEvent.h:

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.

关于 swift NSEvent 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34244865/

相关文章:

swift - 在 Swift 中获取 Objective-C @objc 枚举值的字符串名称?

cocoa - 在cocoa2.0中,@property是否避免了接口(interface)中的变量声明

ios - 将 GMT 时间添加到 ios 中的给定日期时间(来自服务器)

swift - OSX NSTextView 在显示 NSAlert、NSOpenPanel 后变得不可编辑

ios - Swift - 如何 shouldOverrideUrlLoading

macos - 更改Mac OS 10.7 Lion VNC服务器监听端口

python - 是否有可通过 USB key 在 Mac OS X 10.6 上运行的可移植 Python 解释器?

swift - 在 Swift 中打开关闭的 NSWindow 会使应用程序崩溃

objective-c - 在数组上使用 KVC 的 @count 会引发数组中的类的异常

xcode - 声音选择器/macOS 上的系统声音列表