如何在macOS的Swift中全局检测击键? [英] How to detect keystrokes globally in Swift on macOS?

查看:94
本文介绍了如何在macOS的Swift中全局检测击键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我尝试的方法:

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.

推荐答案

看起来像重复标记已被删除,但是我将其汇总到注释部分中的答案也已删除。因此,对于后代:

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

之所以不起作用,是因为.keyDown事件的全局监视器比其他一些事件处理程序(包括有人认为这是重复的。这主要是因为全局.keyDown监视器可用于恶意目的,例如键盘记录程序。因此,还有其他安全措施可确保我们合法:

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)您的应用需要进行代码签名。

1) Your app needs to be code-signed.

2)您的应用需要启用应用沙箱,并且:

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

3)您的应用需要可以在安全性和隐私首选项窗格中的可访问性下进行注册。

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")
}

这将提示用户,使他/她可以选择自动打开适当的首选项窗格,用户可以在其中允许您的应用通过Accessibility API来控制计算机,假设您的应用已签名d未沙盒化,将允许您的全局.keyDown监视器工作。

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.

这篇关于如何在macOS的Swift中全局检测击键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆