Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect keystrokes globally in Swift on macOS?

Tags:

swift

cocoa

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.

like image 767
Toma Avatar asked Aug 31 '17 17:08

Toma


2 Answers

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.

like image 137
Charles Srstka Avatar answered Nov 04 '22 07:11

Charles Srstka


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?

like image 1
Daij-Djan Avatar answered Nov 04 '22 09:11

Daij-Djan