I 'm trying to hook on Keyboard Messages without any success.
I create a test console win32 app:
int _tmain(int argc, _TCHAR* argv[])
{
HOOKPROC hHookProc;
HINSTANCE hinstDLL;
HHOOK hHook;
hinstDLL = LoadLibrary(TEXT("pathtodll\\KeyHook.dll"));
hHookProc= (HOOKPROC)GetProcAddress(hinstDLL, "HookProc");
hHook = SetWindowsHookEx(
WH_KEYBOARD,
hHookProc,
hinstDLL,
0);
while (1) {}
return 0;
}
I've also created a test win32 dll with the HookProc function:
extern __declspec(dllexport) LRESULT CALLBACK HookProc(
int nCode,
WPARAM wParam,
LPARAM lParam
)
{
// process event
//...
MessageBox( NULL,
开发者_如何学运维 TEXT("OK"),
TEXT("OK"),
MB_OK);
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
Everything compiles fine but when I'm trying to debug, it seems that HookProc is never called. Actually in Win 7 the app hangs when i press any key, while in Win Xp HookProc is not called. I do get not NULL hinstDLL, hHookProc, hHook.
What am I misssing?
Instead of performing a blank while loop after calling SetWindowsHookEx()
, try having the loop pump the calling thread's message queue instead, via Peek/GetMessage()
. Some hooks run in the context of the thread that installs them, so the OS has to be able to switch to that thread when needed.
Couple of issues here:
while (1) {}
Don't do this: your code now has a busy (infinite) loop that will effectively make the app unresponsive (and probably make the whole desktop seem sluggish too). The reason that GetMessage works here is simply because it hands control back to the OS, which will put the thread to sleep instead of running busily. You'll probably get the same effect just by calling Sleep(...), which will also return control back to the OS but without pumping messages. For test code, something like getchar() can work well here, it will gracefully block till you hit Enter in the console window. MessageBox() can also work here.
extern __declspec(dllexport) LRESULT CALLBACK HookProc(
{
MessageBox( NULL,
TEXT("OK"),
TEXT("OK"),
MB_OK);
Another problem: you generally never want to do anything 'complex' in a hook callback - just do the bare minimum to process the message, and return ASAP. You certainly don't ever want to block, which is what MessageBox does. For debugging purposes, OutputDebugString() or some other debug-oriented API that doesn't block is the way to go.
精彩评论