转换虚拟键码到Unicode字符串
我有一些代码,我一直在使用获取当前的键盘布局,并将虚拟键码转换为字符串。这在大多数情况下效果很好,但我在某些特定情况下遇到问题。让这个灯亮的是德国QWERTZ键盘上退格键旁边的重音键。 http://en.wikipedia.org/wiki/File:KB_Germany.svg转换虚拟键码到Unicode字符串
该键生成的VK代码我期望kVK_ANSI_Equal
,但是当使用QWERTZ键盘布局时,我不会再描述。它最终成为一个死钥匙,因为它应该由另一把钥匙组成。有什么方法可以抓住这些情况并做适当的转换吗?
我目前的代码如下。
TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
if(keyboardLayout)
{
UInt32 deadKeyState = 0;
UniCharCount maxStringLength = 255;
UniCharCount actualStringLength = 0;
UniChar unicodeString[maxStringLength];
OSStatus status = UCKeyTranslate(keyboardLayout,
keyCode, kUCKeyActionDown, 0,
LMGetKbdType(), kUCKeyTranslateNoDeadKeysBit,
&deadKeyState,
maxStringLength,
&actualStringLength, unicodeString);
if(actualStringLength > 0 && status == noErr)
return [[NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength] uppercaseString];
}
这关键是一个死键,你可以看到,如果你自己尝试一下或看与德国积极布局的键盘显示程序。
在Mac上,输入死锁的实际字符而不用另一个字符组成的方法是在其后按空格。因此请尝试:关闭kUCKeyTranslateNoDeadKeysBit
,如果UCKeyTranslate
设置了死锁状态,请在它后面翻译一个空格。
编辑(由提问者加)
只是为了未来的人来说,这里是正确的解决方案的固定代码。
TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
if(keyboardLayout)
{
UInt32 deadKeyState = 0;
UniCharCount maxStringLength = 255;
UniCharCount actualStringLength = 0;
UniChar unicodeString[maxStringLength];
OSStatus status = UCKeyTranslate(keyboardLayout,
keyCode, kUCKeyActionDown, 0,
LMGetKbdType(), 0,
&deadKeyState,
maxStringLength,
&actualStringLength, unicodeString);
if (actualStringLength == 0 && deadKeyState)
{
status = UCKeyTranslate(keyboardLayout,
kVK_Space, kUCKeyActionDown, 0,
LMGetKbdType(), 0,
&deadKeyState,
maxStringLength,
&actualStringLength, unicodeString);
}
if(actualStringLength > 0 && status == noErr)
return [[NSString stringWithCharacters:unicodeString length:(NSUInteger)actualStringLength] uppercaseString];
}
此代码用于密钥绑定翻译。因此,在这种情况下,密钥在正常输入之外是可用的。我在HID级别上抓住它,但我需要一种方式向用户展示绑定的密钥。我如何知道对于QWERTZ布局,该虚拟键是那个键帽? –
这里是固定的代码,非常感谢Peter,https://github.com/OpenEmu/OpenEmu/commit/a59dddfa669ab0e2872f79a6443c45e2a2d87253 –
@JoshuaWeinberg:我更正了你添加到我的答案中的代码;您将长度转换为错误的类型。 –
如果您没有设置kUCKeyTranslateNoDeadKeysMask代替kUCKeyTranslateNoDeadKeysBit,因为而前者与该位掩码启用实际上后者被定义为0? – rdb