Objective-C / Cocoa: detect all keystrokes

Is it possible to run the method every time the user presses a key. Basically I want to make sound like on iPhone or iPad when a key is pressed. I don’t want to detect keystrokes in my window or in a specific control, I want to detect ALL keystrokes (for example, when they type in Safari or something like that. ) I don’t need to know what the key is.

thanks

+6
source share
3 answers

Use CGEventTapCreate here:

https://developer.apple.com/library/mac/#documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html

Or use the NSEvents addGlobalMonitorForEventsMatchingMask:handler: described here:

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/nsevent_Class/Reference/Reference.html

NSEvent example:

 [NSEvent addGlobalMonitorForEventsMatchingMask:(NSKeyDownMask) handler:^(NSEvent *event){ [self keyWasPressedFunction: event]; //Or just put your code here }]; 

I would say that NSEvents is easier ...

Note:

For security reasons, Apple requires that “Enable access for assistive devices” be included in System Preferences in order to use the broadcast of the above methods.

+11
source

You can come close to the Quartz event, but some key presses are not detected even with one for security.

If you tell us about the broader goal you have in mind, we can offer alternatives. Are you trying to create a global hotkey for your application? Are you writing a keylogger or malware? What?

+3
source

Use NSEvents addGlobalMonitorForEventsMatchingMask:handler:

In applicationDidFinishLaunching add the following code, build and go!

 [NSEvent addGlobalMonitorForEventsMatchingMask:(NSKeyDownMask) handler:^(NSEvent *event){ NSLog(@"%@", event.characters); }]; 

Apple requires "Enable access for assistive devices" in System Preferences.

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/nsevent_Class/Reference/Reference.html

+1
source

Source: https://habr.com/ru/post/914435/


All Articles