Convert key code into key equivalent string

后端 未结 2 1158
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 07:40

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

相关标签:
2条回答
  • 2020-12-10 07:47

    UCKeyTranslate is probably what you are after https://developer.apple.com/library/mac/#documentation/Carbon/Reference/Unicode_Utilities_Ref/Reference/reference.html

    0 讨论(0)
  • 2020-12-10 07:59

    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);
    }
    
    0 讨论(0)
提交回复
热议问题