简体   繁体   中英

How can I set up a CBT hook on a Win32 console window?

I've been trying to set up a CBT hook for my C++ Console application with the following code:

 ...includes...

 typedef struct _HOOKDATA
 {
    int type;
    HOOKPROC hookproc;
    HHOOK hhook;
 }_HOOKDATA;

 _HOOKDATA hookdata;

 //CBT
 LRESULT CALLBACK CBTProc(int code, WPARAM wParam, LPARAM lParam)
 { 
    //do not proccess message
    if(code < 0)
    {
       cout<<"code less than 0"<<endl;
       return CallNextHookEx(hookdata.hhook,code,wParam,lParam);
    }

    switch(code)
   {
      case HCBT_ACTIVATE:
           break;
      case HCBT_CREATEWND:
           cout<<"CREATEWND"<<endl;
           break;
      case HCBT_MINMAX:
           cout<<"MINMAX"<<endl;
           break;
      default: //unknown
           cout<<"DEFAULT"<<endl;
           break;
   }

   return CallNextHookEx(hookdata.hhook, code, wParam, lParam);
}

int main()
{
   hookdata.type = WH_CBT; 
   hookdata.hookproc = CBTProc; 
   hookdata.hhook = ::SetWindowsHookEx(hookdata.type, CBTProc, 
                                    GetModuleHandle( 0 ), GetCurrentThreadId());

   if(hookdata.hhook == NULL)
   {
     cout<<"FAIL"<<endl;
     system("pause");
   }

   system("pause");
   return 0;
}

The program seems to be working because there is not compile errors nor run time errors. Also I do not get a 'FAIL' message stated in the main() function meaning SetWindowHookEx is working OK. However, I don't get any of the messages stated in the CBTProc function; not even the 'DEFAULT' message. Can anyone pin-point what is the logic error in the code?

Thanks.

The problem is that SetWindowHookEx is based upon the Win32 message handling model. Console windows are children of the Kernel itself and do not create their own message pumps or windows.

AFAIK doing what you want directly is not possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM