How can I convert a key code, such as kVK_ANSI_1
into a string that I can pass to setKeyEquivalent
(so for kVK_ANSI_1
, I'd get @"1"
)? And why are there two ways to specify keys anyway? It would make more sense to have just one representation.
Asked
Active
Viewed 3,482 times
6

houbysoft
- 32,532
- 24
- 103
- 156
-
1There are two ways to specify keys because `kVK_ANSI_1` represents a position on the keyboard (where the "1" key is located on an ANSI-standard US keyboard), whereas "1" represents the character typed (which may or may not come from `kVK_ANSI_1`, depending on your keyboard layout). – jlstrecker Mar 22 '14 at 01:29
2 Answers
8
I ended up using the following function found here.
/* Returns string representation of key, if it is printable.
* Ownership follows the Create Rule; that is, it is the caller's
* responsibility to release the returned object. */
CFStringRef createStringForKey(CGKeyCode keyCode)
{
TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
CFDataRef layoutData =
TISGetInputSourceProperty(currentKeyboard,
kTISPropertyUnicodeKeyLayoutData);
const UCKeyboardLayout *keyboardLayout =
(const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
UInt32 keysDown = 0;
UniChar chars[4];
UniCharCount realLength;
UCKeyTranslate(keyboardLayout,
keyCode,
kUCKeyActionDisplay,
0,
LMGetKbdType(),
kUCKeyTranslateNoDeadKeysBit,
&keysDown,
sizeof(chars) / sizeof(chars[0]),
&realLength,
chars);
CFRelease(currentKeyboard);
return CFStringCreateWithCharacters(kCFAllocatorDefault, chars, 1);
}
2
UCKeyTranslate is probably what you are after https://developer.apple.com/library/mac/#documentation/Carbon/Reference/Unicode_Utilities_Ref/Reference/reference.html

Michelle Six
- 655
- 3
- 13