Rafał
Rafał

Reputation: 1287

Convert character to key code in cocoa or carbon

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?

Upvotes: 3

Views: 2912

Answers (1)

jscs
jscs

Reputation: 64022

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.

Upvotes: 5

Related Questions