Virtual key code of ALT KEY

Viewed 3244

I am making hooks and catching keyboard virtual key codes, according to MSDN, these are the key codes that exist.

Every key code works fine as i will give an example down below of my code.

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

HHOOK altKey;
KBDLLHOOKSTRUCT kbdHK;
MSG message;

LRESULT CALLBACK kbdProc(int nCode, WPARAM wPar, LPARAM lPar);

int main(int argc, char *argv[]) {
  altKey = SetWindowsHookEx(WH_KEYBOARD_LL, kbdProc, NULL, 0);

  while(GetMessage(&message, NULL, 0, 0) > 0){
    TranslateMessage(&message);
    DispatchMessage(&message);
  }
  return 0;
}

LRESULT CALLBACK kbdProc(int nCode, WPARAM wPar, LPARAM lPar){

  if(nCode >= 0){
    if(wPar == 256){
      kbdHK = *(KBDLLHOOKSTRUCT *)lPar;
      if(kbdHK.vkCode == 0x20){
        printf("spacebar pressed!!\n");
      }
    }
  }
  return CallNextHookEx(NULL, nCode, wPar, lPar);
}

But when I replace the virtual key code with 0x12 which is ALT KEY according to MSDN, I can't get a result back. What could be the problem?

Edit:

When I use this line of code, I can get the scanCode for every key but not for alt key again which is interesting.

printf("%d", kbd.scanCode); 
1 Answers

I suggest hooking the WM_SYSKEYDOWN messages, and noting that the values correspond to constants that more often have identifiers (VK_MENU, in this case). After all, as programmers we're taught early on not to use magic numbers!

WM_SYSKEYDOWN message

Posted to the window with the keyboard focus when the user presses the F10 key (which activates the menu bar) or holds down the ALT key and then presses another key.

Another option, as pointed out in the comments, is to use GetAsyncKeyState. Your concerns that you won't be able to use vkCode seem strange, as GetAsyncKeyStates parameter is the virtual key code, after all, so the code you'd be using would be along the lines of:

short result = GetAsyncKeyState(VK_MENU);
if (!result) {
    // no alt keystrokes since last call
}

This is the only way you'll be able to distinguish between left alt (VK_LMENU) and right alt (VK_RMENU) keys, but it's not the window-loop way. Now you have both.

Related