Where can I find a list of key codes for use with Cocoa's NSEvent class?

I'm looking for a comprehensive list of the available key codes that can be used with Cocoa's NSEvent class. The NSEvent class has a keyCode property, which is defined as unsigned short. The following code, when placed in an appropriate UI object, will echo the key codes as they are pressed:

- (void)keyDown:(NSEvent *)theEvent
{
    NSLog(@"%d", [theEvent keyCode]);
}

From this code, I can easily see which codes match certain keys, but I would like to find an official document somewhere that lists all of them. I expected Apple to have a header file somewhere that looked like this:

enum {
    ...
    NSKeyCodeLeftArrow = 123,
    NSKeyCodeRightArrow = 124,
    ...
};

But if there is one, I have yet to find it.


Solution 1:

Here you go. It's a map of all the virtual key-codes on the US extended keyboard layout, from the old Inside Macintosh: Text. Most of the key codes are still currently, although I suspect that the very newest Apple keyboards—those with media keys—may have changed a few of the function keys.

Note: ISO and non-extended keyboards may have different key codes for some keys. If you have such a keyboard, try Peter Maurer's Key Codes application. His site is down, so here's my copy.

Solution 2:

As far as I know, there is no enum or list of key codes. However, to get similar behavior, you can call interpretKeyEvents: in keyDown: which will call appropriate action methods, all of which are documented in NSResponder (e.g. moveLeft:, insertTab:, etc.)

Solution 3:

To include HIToolbox/Events.h (as mentioned in berrange's answer) in XCode 4 you just need to go to Link Binaries with Libraries and add the Carbon framework (which includes HIToolbox) and then import the main Carbon header in the file where you are checking the keyCodes.

#import <Carbon/Carbon.h>

It took me a second to figure out that I couldn't import HIToolbox/Events.h directly so I thought I'd post this in case it helps someone.

Solution 4:

According to this forum topic, the constants are available in HIToolbox/Events.h

http://forums.macrumors.com/showthread.php?t=780577

They have conveniently copy+pasted the entire set of constants into the forum too. Otherwise the header is available here:

/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h

Solution 5:

For Swift, import Carbon.HIToolbox.Events and then use the constants directly:

import Carbon.HIToolbox.Events

let keyCode = kVK_ANSI_A

For a list of all codes, go to the definition of Carbon.HIToolbox.Events:

screenshot