Handling keyboard input in win32, WM_CHAR or WM_KEYDOWN/WM_KEYUP?

后端 未结 3 631
鱼传尺愫
鱼传尺愫 2021-01-30 23:07

So in the text editor program that i\'ve been working on, I\'ve used WM_CHAR to process input from the keyboard. However, I found that some of the character mesages are not reco

3条回答
  •  执念已碎
    2021-01-30 23:36

    The helpful message above inspired me to create this snippet, which gives you a human-readable indication of what key was pressed from any WM_KEYDOWN/WM_KEYUP/WM_SYSKEYDOWN/WM_SYSKEYUP independent of the state of the modifier keys.

    // get the keyboard state
    BYTE keyState[256];
    GetKeyboardState(keyState);
    // clear all of the modifier keys so ToUnicode will ignore them
    keyState[VK_CONTROL] = keyState[VK_SHIFT] = keyState[VK_MENU] = 0;
    keyState[VK_LCONTROL] = keyState[VK_LSHIFT] = keyState[VK_LMENU] = 0;
    keyState[VK_RCONTROL] = keyState[VK_RSHIFT] = keyState[VK_RMENU] = 0;
    // convert the WM_KEYDOWN/WM_KEYUP/WM_SYSKEYDOWN/WM_SYSKEYUP to characters
    UINT scanCode = (inLParam >> 16) & 0xFF;
    int i = ToUnicode(inWParam, scanCode, keyState, outBuf, inOutBufLenCharacters, 0);
    outBuf[i] = 0;
    

    By modifying the keyState array so that all the modifier keys are clear, ToUnicode will always output the unshifted key you pressed. (So, on the English keyboard you'll never get '%' but always '5') as long as it's a human readable key. You still have to do the VK_XXX checking to sense the arrow and other non-human readable keys however.

    (I was trying to rig up a user editable "hot key" system in my app, and the distinction between WM_KEYXXX and WM_CHAR was making me nuts. The code above solved that problem.)

提交回复
热议问题