Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C/Cocoa: Detect all keypresses

Is it possible to run a method every time the user presses a key. Basically I want to run a sound like on the iPhone or iPad when a key is pressed. I do not want to detect key presses in my window or in a certain control, I want to detect ALL presses (such as when they are typing in Safari or something. I do not need to know what the key is.

Thanks

like image 270
Oliver Cooper Avatar asked Apr 29 '12 01:04

Oliver Cooper


1 Answers

Use CGEventTapCreate documented here:

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

Or use NSEvents addGlobalMonitorForEventsMatchingMask:handler: documented 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 NSEvents are easier...

Note:

For security reasons, Apple requires you have "Enable access for assistive devices" turned on in System Preferences, in order to use ether of the above methods.

like image 167
Teak Avatar answered Oct 19 '22 03:10

Teak