以下代码段用于在用户键入密钥时显示消息。即使重点不在于应用程序。但是以下代码似乎存在问题。它不会使用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);
}
但是窗口不会调用函数LowLevelKeyboardProc
。我不明白原因,但我确信问题出在钩子函数中hInst
。我如何初始化它?
直到现在,我看到的输出是Inside function setWinHook !
答案 0 :(得分: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;
}