如何正确挂钩WM_COMMAND

时间:2013-12-23 21:58:47

标签: c++ winapi hook

我正在尝试在mfc窗口中挂钩按钮。我使用了WM_COMMAND和WM_NOTIFY。为了测试,如果单击该按钮,则钩子必须创建一个消息框。问题是它不会对按钮点击做出反应。 这是对WM_COMMAND和WM_NOTIFY作出反应的代码:

LPMSG msg = (LPMSG)lParam;

    switch( msg->message )
    {
    case WM_COMMAND:
        MessageBox( NULL,"HOOK","YOOOO",MB_ICONEXCLAMATION );
        break;
    case WM_NOTIFY:
        MessageBox( NULL,"HOOK","YOOOOO",MB_ICONEXCLAMATION );
        break;
    }

这是破洞的代码:

#include <Windows.h>
#include "FindingWindow.h"
#pragma comment( linker,"/SECTION:.SHARED,RWS" )
#pragma data_seg( ".SHARED" )
CaptureTextWindow* ctw;
HHOOK hook = 0;
HMODULE hInstance = 0;
HWND hWndServer = NULL;
#pragma data_seg()

static LRESULT CALLBACK msghook(int nCode, WPARAM wParam, LPARAM lParam);
__declspec(dllexport) BOOL clearMyHook(HWND hWnd);

BOOL APIENTRY DllMain( HINSTANCE hInst, DWORD ul_reason_for_call, LPVOID lpReserved )
{
    switch( ul_reason_for_call )
    {
    case DLL_PROCESS_ATTACH:
        hInstance =  hInst;
        return TRUE;
    case DLL_PROCESS_DETACH:
        if(hWndServer != NULL)
          clearMyHook(hWndServer);
        return TRUE;
    }   
    return TRUE;
}



__declspec(dllexport) BOOL WINAPI setMyHook(HWND hWnd)
  {
   if(hWndServer != NULL)
      return FALSE;
   hook = SetWindowsHookEx(
                           WH_CALLWNDPROC,
                           (HOOKPROC)msghook,
                           hInstance,
                           0);
   if(hook != NULL)
   { /* success */
      hWndServer = hWnd;
      return TRUE;
   } /* success */
   return FALSE;
}
__declspec(dllexport) BOOL clearMyHook(HWND hWnd)
{
    if(hWnd != hWndServer)
       return FALSE;
    BOOL unhooked = UnhookWindowsHookEx(hook);
    if(unhooked)
       hWndServer = NULL;
    return unhooked;
}

static LRESULT CALLBACK msghook( int nCode,        // hook code
                                   WPARAM wParam ,  // message identifier
                                   LPARAM lParam )  
{
    if( nCode < 0 )
    {
        CallNextHookEx( hook, nCode, wParam, lParam );
        return 0;
    }
    LPMSG msg = (LPMSG)lParam;

    switch( msg->message )
    {
    case WM_COMMAND:
        MessageBox( NULL,"HOOK","YOOOO",MB_ICONEXCLAMATION );
        break;
    case WM_NOTIFY:
        MessageBox( NULL,"HOOK","YOOOOO",MB_ICONEXCLAMATION );
        break;
    }

    return CallNextHookEx( hook, nCode, wParam, lParam );
}

我不仅使用WM_COMMAND因为我认为它会起作用,但它没有。谢谢你回答。

1 个答案:

答案 0 :(得分:2)

WH_CALLWNDPROC hooklParam类型为CWPSTRUCT。您的CallWndProc应如下所示:

// ...
const CWPSTRUCT& cwps = *(CWPSTRUCT*)lParam;
switch ( cwps.message ) {
case WM_COMMAND:
    MessageBox( ... );
    break;
// ...