C++ Win32: Converting scan code to Unicode character
When I switch to Russian layout in Windows 7 and press ; key on the keyboard, I get Russian letter ж on the screen.
I am working on a application where I need to detected pressed keys and draw text on the screen. The requirement is handle all supported languages. This is my code:
// I scan the keyboard for pressed keys
for (short key = KEY_SCAN_MIN; key <= KEY_SCAN_MAX; ++key)
{
if (GetAsyncKeyState(key) & 0x8000)
{
// When I detect a pressed key, I convert the scan code into virtual key.
// The hkl is current keyboard layout parameter, which is Russian.
UINT virtualKey = MapVirtualKeyEx((UINT)key, MAPVK_VK_TO_CHAR, hkl);
// Next I get the state of th开发者_StackOverflow社区e keyboard and convert the virtual key
// into Unicode letter
if (!GetKeyboardState(kbrdState))
{
continue;
}
// unicode is defined as wchar_t unicode[2];
int result = ToUnicodeEx(virtualKey, key, (BYTE*)kbrdState, unicode, 2, 0, hkl);
Everything works great except a couple letters in Russian and I cannot figure out why. One specific letter that does not work is ж. When I attempt to translate its scan code, the translation is б, which is a different Russian letter.
I have spent entire day debugging this issue and do not get too far. When I press this Russian key I get 168 for scan code and 1078 for the virtual key. I did this small test to convert the letter back to the virtual key.
short test = VkKeyScanEx(L'ж', hkl);
The value of variable test is 1078! I do not understand why converting letter ж to virtual key gives me 1078 but converting 1078 virtual key (using the same keyboard layout) gives me б.
I always use WM_CHAR
to read scan codes as it does the translation work for you and returns the final character in UTF-16. Works with all languages, even ones with which it takes more than one key press to represent a single character.
精彩评论