将键代码转换为键等效字符串 [英] Convert key code into key equivalent string

查看:97
本文介绍了将键代码转换为键等效字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将键码(例如 kVK_ANSI_1 )转换为可传递至 setKeyEquivalent 因此 kVK_ANSI_1 ,我会得到 @1)?为什么有两种方法来指定键?

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.

推荐答案

我最后使用下面的函数找到此处

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);
}

这篇关于将键代码转换为键等效字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆