Post

Detect Keystrokes globally (macOS Keystroke logging)

Envirnoment:

macOS: 12.2 Beta Xcode: 13.2.1

Prerequisites:

Excerpt from Charles Srstka answer on Stackover Flow : Link

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.

Prompt for user’s permission:

AccessibilityAccessPrompt

1
2
3
4
5
6
7
8
9
@discardableResult
func acquirePrivileges() -> Bool {
    let accessEnabled = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary)

    if accessEnabled != true {
        print("You need to enable the keylogger in the System Prefrences")
    }
    return accessEnabled
}

The above code will present the alert for permission, navigate to Privacy tab under System Preferences > Security & Privacy and clicking on the App’s checkbox should enable accessibility for the app.

AccessibilityPermissionAllowed

Using the below code will allow adding global monitoring for the .keyDown event. The event will not be triggered if you try to enter a password on any website. [Now aware of any public API or workaround to tackle that for now 😉]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@main
class AppDelegate: NSObject, NSApplicationDelegate {

    private var monitor: Any?

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        acquirePrivileges()
        monitor = NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { event in
            print(event)
        }
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
        return true
    }
}
This post is licensed under CC BY 4.0 by the author.