How do I convert a character (or one letter NSString) into corresponding key code that would generate it using currently selected keyboard layout with cocoa or carbon?
-
3You probably can't do this reliably, since it's not a 1:1 relationship, e.g. there are characters that may be generated by more than one key, such as the numeric digits 0-9. – Paul R Oct 10 '11 at 20:59
-
Possible duplicate of: [How to convert ASCII character to CGKeyCode?](https://stackoverflow.com/questions/1918841/how-to-convert-ascii-character-to-cgkeycode) – pkamb Dec 04 '19 at 11:39
1 Answers
This is a tough thing to figure out. It depends heavily on keyboard layout and possibly other things. A couple of articles on it have disappeared from the web in the last year or two.
The only place that I have been able to find the list of key codes in the official docs is in <HIToolbox/Events.h> (Peter Hosey has also posted a short article about this), The other thing about them is that there's a set that are device-dependent and a set that aren't. For example, VK_ANSI_A
only corresponds to the character 'A' on a US keyboard; on the other hand, kVK_LeftArrow
is supposed to be the same on any Apple keyboard.
Other "function" keys are similar. As far as I can tell, though, the key codes that correspond most directly to characters, and therefore change their value depending on keyboard layout, are actually constant as far as location. I'm not sure if that's clear...I believe that it's the case that the key code for the letter key in the lower-left-hand corner of any Apple keyboard is VK_ANSI_Z
, but I'm not really sure.
Allan Odgaard has an article about the hoops he had to jump through to decipher keypresses: https://sigpipe.macromates.com/2005/deciphering-an-nsevent/ He gives code for the heuristic methods he ended up using.

- 63,694
- 13
- 151
- 195
-
Is this still the case today? I was trying to decipher the keycode if it was a media key. I added a local monitor for nskeydown events. – Noitidart Oct 11 '15 at 04:48