Wednesday, January 30, 2013

low level keyboard handlers

the following code allows us to write windows C++ code to capture low level key event. 
for a complete virtual key code, can refer to this page: 
 
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx
 
 
 
1) header files required:
need to include stdio.h file, and also need to include Winuser.h file. 
 
2) global variables:
HHOOK hKeyHook;
KBDLLHOOKSTRUCT kbdStruct; 
 
 
3) define key event function, note the formatting in if condition. 
 
char str[255]; //debug str 
LRESULT WINAPI KeyEvent(int nCode, WPARAM wParam, LPARAM lParam)
{
 if( (nCode == HC_ACTION) && ((wParam == WM_SYSKEYDOWN) || (wParam == WM_KEYDOWN)) )
 {
  kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
  sprintf_s(str,"%X\t%c\n", (unsigned int)kbdStruct.vkCode, (char)kbdStruct.vkCode);
  OutputDebugStringA(str);

 }
 return CallNextHookEx(hKeyHook, nCode, wParam, lParam);
}
 
 
 
4) add hook functions
hKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)KeyEvent, GetModuleHandle(NULL), 0);
    MSG msg;

    while(TRUE)
    {
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        if(msg.message == WM_QUIT)
            break;

        render_frame();
    }

    
 
 UnhookWindowsHookEx(hKeyHook);

    return (int)msg.wParam;
5) fix some compiling errors:
http://www.yelsew.com/c2065_wh_keyboard_ll.html 
 
in visual studio property window, in the C++'s preprocessor need to add the following: 
_WIN32_WINNT=0x0500
to ensure we are telling the compiler we are creating code for newer version windows.