Convert key code into key equivalent string

China☆狼群 提交于 2019-11-27 03:33:19

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/12547007/convert-key-code-into-key-equivalent-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!