views:

457

answers:

2

I am trying to retrieve messages for another application with a Windows hook. I have setup a WH_GETMESSAGE hook with SetWindowsHookEx. This is done via a DLL. In my GetMsgProc fuction (that should be called whenever the target application recieves a message) I want to take action based on the type of message. However I am having trouble with this if statement.

LRESULT CALLBACK MessageHookProcedure(int code, WPARAM wParam, LPARAM lParam){
    if(((MSG*)lParam)->message == WM_COMMAND){
     MessageBox(NULL,L"The hook procedure was called",L"Test Window",MB_OK);
    }

    return CallNextHookEx(g_MessageHook,code,wParam,lParam);
}

For some reasone the MessageBox is never created. I know the application is recieving WM_COMMAND messages from Spy++. If I take out the IF statement the MessageBox is created over and over as it recieves a variety of messages. I am a new C++ programmer so any help is greatly appreciated. Thanks

+1  A: 

Are you sure that you're hooking the correct window or the correct message, respectively? Under some circumstances WM_SYSCOMMAND or WM_MENUCOMMAND is generated instead of WM_COMMAND.

Your code looks fine, have you also tried dumping the incoming messages into console?

arul
I think you are right, I must be hooking the wrong window. I will check my logic. Thanks for looking at my code.
JohnG
A: 

The LPARAM here is a pointer to CWPSTRUCT which in turn contains message parameter. The following should work.

LRESULT CALLBACK MessageHookProcedure(int code, WPARAM wParam, LPARAM lParam){
    if(((CWPSTRUCT*)lParam)->message == WM_COMMAND){
        MessageBox(NULL,L"The hook procedure was called",L"Test Window",MB_OK);
    }

    return CallNextHookEx(g_MessageHook,code,wParam,lParam);
}
Canopus
Your comment helped too. I actually got the functionality I needed with a WH_CALLWNDPROC hook which uses the CWPSTRUCT as you mentioned. I also was hooking the wrong window. :) Thanks for the help!
JohnG