I'm trying to set a WH_CBT
hook, and it return 0 all the time.
I checked for error, and I got error 1428. I researched a little and found out that I have a problem with the hMod
parameter, though I can't see what should I put in it instead of null
. Does anyone know what I am doing wrong?
This is my code:
#include "stdafx.h"
#include "Windows.h"
#include <iostream>
using namespace std;
HHOOK hookHandle;
LRESULT CALLBACK CBTProc( int nCode, WPARAM wParam, LPARAM lParam);
int _tmain(int argc, _TCHAR* argv[])
{
hookHandle = SetWindowsHookEx(WH_CBT,CBTProc,NULL,0);
if(hookHandle == NULL)
{
cout << "ERROR CREATING 开发者_高级运维HOOK: ";
cout << GetLastError() << endl;
getchar();
return 0;
}
MSG message;
while(GetMessage(&message, NULL, 0, 0) != 0)
{
TranslateMessage( &message );
DispatchMessage( &message );
}
cout << "Press any key to quit...";
getchar();
UnhookWindowsHookEx(hookHandle);
return 0;
}
LRESULT CALLBACK CBTProc( int nCode,WPARAM wParam, LPARAM lParam)
{
cout << "hello" << endl;
return CallNextHookEx(hookHandle, nCode,
wParam, lParam);
}
P.S. I apologize if the code has stupid elements about it. I'm not a newbie to programming, just to C++.
If you specify 0 for the threadid that specifies the hook to be global. For that to work, the hook needs to be injected into other processes. This means the hook needs to be exposed from a DLL. You need to either move the hook procedure to a dll, or specify a thread in your process.
Use GetModuleHandle(NULL)
and GetCurrentThreadId()
to get the handle and the thread id you need to pass to that function.
Sample:
hookHandle = SetWindowsHookEx(WH_CBT,CBTProc,
GetModuleHandle(NULL),
GetCurrentThreadId());
As Logan says, that would hook only the current process. You need to put the code in a dll to develop a system hook.
I know that this is very old post, but I was fighting with the simmilar issue. I wanted to track size and location changes for the "Shell_traywnd" window and I found a solution in this thread. I belive that it will help for someone else.
精彩评论