displaying a message when the user taps a key

廉价感情. 提交于 2019-12-11 03:14:06

问题


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 !


回答1:


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;
}


来源:https://stackoverflow.com/questions/10750037/displaying-a-message-when-the-user-taps-a-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!