Tuesday, April 8, 2008

[win32] Ascii, Unicode, Scan code, Virtual key

... and other keyboard nightmares :-)

I found two very useful functions in the Win32 API: ToUnicodeEx and ToAsciiEx. It converts from a virtual key code and a scan code to a unicode or ascii character. It can be used directly from a WM_KEYDOWN (or KEYUP) message.

Here is a quick code snippet:


uint scancode = (lParam >> 16) & 0xFF;
BYTE keyboardState[256];
GetKeyboardState(keyboardState);
char charvalue[2];
if (ToAsciiEx(wParam, scancode, keyboardState, (LPWORD)&charvalue[0], 0, GetKeyboardLayout(0)) == 1) {
  onKeyPressed(charvalue[0]);
}


Also check out this blog for more info.

2 comments:

  1. Yay! Thanks to your blog post, my GUI can take internationalized input now :)
    Cheers!

    ReplyDelete