2

以下代码段旨在在用户键入密钥时显示消息。即使焦点不在应用程序上。但是下面的代码似乎有问题。它不会调用在 windows 的钩子链中注册的函数。我想问题出在HINSTANCE hInst. 我应该如何修改下面的代码,以便在用户点击一个键时能够看到消息。

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

但是 windows 不调用该函数LowLevelKeyboardProc。我不明白原因,但我确信问题出hInst在钩子函数中。我需要如何初始化它?

到目前为止,我看到的输出是Inside function setWinHook !

4

1 回答 1

1

下面是一个 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;
}
于 2012-05-25T07:22:06.577 回答