Objective-C/Cocoa: Detect all keypresses

cocoa, keypress, macos, objective-c

Solution

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.

Problem

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

Original source