How to detect keystrokes globally in Swift on macOS?

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

Here is what I tried:

NSEvent.addGlobalMonitorForEvents(matching: [.keyDown]) { (event) in     print(event.keyCode) } 

Unfortunately, it does not print anything.

And no, it's not a duplicate of this, that question is about modifier keys, my question is about keystrokes.

回答1:

Looks like the "duplicate" mark got removed, but so has the answer that I kludged into the comments section. So, for posterity:

The reason this doesn't work is because global monitors for .keyDown events require more permissions than some of the other event handlers, including the one that somebody thought this was a duplicate of. This is mainly because global .keyDown monitors can be used for nefarious purposes, such as keyloggers. So there are additional security measures in place to make sure we're legit:

1) Your app needs to be code-signed.

2) Your app needs to not have the App Sandbox enabled, and:

3) Your app needs to be registered in the Security and Privacy preference pane, under Accessibility.

The third one of these things has to be enabled by the user, but you can nudge them in that direction with this code:

let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String : true] let accessEnabled = AXIsProcessTrustedWithOptions(options)  if !accessEnabled {     print("Access Not Enabled") } 

This will prompt the user, giving him/her the option to automatically open the appropriate preference pane where the user can allow your app to control the computer via the Accessibility API, which, assuming your app is signed and not sandboxed, will allow your global .keyDown monitor to work.



回答2:

if you only want global hotkey support all this is unnecessary (and not all random key or mouse events) you can do that easily with the hotkey API. look at e.g. PTHotkey :)

or a newer api .. seee also: How to implement shortcut key input in Mac Cocoa App?



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!