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

查看:19
本文介绍了如何在 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")
}

这将提示用户,让他/她选择自动打开适当的首选项窗格,用户可以在其中允许您的应用程序通过辅助功能 API 控制计算机,假设您的应用程序已签名而不是沙盒,允许您的全局 .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天全站免登陆