6

I did set the necessary privileges for the app, and for some events it is working.

For instance:

NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged) { print("\($0)") }

works, but

NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { print("\($0)") }

doesn't.

So I am wondering, is it possible at all to listen globally for any keypress?

schnesim
  • 441
  • 1
  • 3
  • 17

2 Answers2

8

After checking the privileges via

let accessEnabled = AXIsProcessTrustedWithOptions( [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary)

I found out, that due to the program running through the Xcode debugger granting the privileges to the app was not enough, I also had to give the privileges to Xcode itself.

schnesim
  • 441
  • 1
  • 3
  • 17
3

schnesim is right!!! but one thing that the answer failed to mention is that every time you change something in a running section of code, you have to go back into preferences and disable, then reenable the permission for the app(not for xcode though) I struggled with that for hours.

  • To future readers: A fix for that is located here: https://stackoverflow.com/questions/49716420/adding-a-global-monitor-with-nseventmaskkeydown-mask-does-not-trigger – 9 Guy Feb 17 '23 at 22:07
  • It will ask you for your password on every build, but you can fix that by selecting "always allow" on the prompt – 9 Guy Feb 17 '23 at 22:08