c++cwinapisetwindowshookexhinstance

displaying a message when the user taps a key


The following snippet is meant to display the message when the user types a key. Even when the focus is not on the application. But there seems to be a problem with the following code. It doesn't call the function registered in the hook-chain with the windows. I guess the problem is with HINSTANCE hInst. How should I modify the below code so that I am able to see the message as the user taps a key.

// Global Variables
static HHOOK handleKeyboardHook = NULL;
HINSTANCE hInst = NULL;

void TestKeys_setWinHook // i call this function to activate the keyboard hook
  (...) {
    hInst = GetModuleHandle(NULL);
    handleKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, hInst, 0); // LowLevelKeyboardProc should be put in the hook chain by the windows,but till now it doesn't do so.
    printf("Inside function setWinHook !");
}

// the following function should be called when the user taps a key.

static LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
  printf("You pressed a key !\n");
  return CallNextHookEx(handleKeyboardHook, nCode, wParam, lParam);
}

But the windows doesn't call the function LowLevelKeyboardProc. I don't understand the reason but I am sure that the problem is with hInst in the hook function. How do i need to initialize it ?

Till now, output that I see is Inside function setWinHook !


Solution

  • Here's an example of a LowLevelKeyboardProc.

    HHOOK hHook;
    
    LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam);
    {
        printf("You pressed a key!\n"); 
        return CallNextHookEx(hHook, nCode, wParam, lParam);
    }
    
    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
    {
      hHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, hInstance, 0);
      MSG msg;
      while(GetMessage(&msg, NULL, 0, 0))
      {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
      }
      return msg.wParam;
    }