1. 程式人生 > >C++Builder實現滑鼠鉤子

C++Builder實現滑鼠鉤子

DLL中的程式碼:

#define WM_KEY_HOOK    WM_USER+200  //自定義訊息



extern "C" {
  __declspec(dllexport)  BOOL APIENTRY StartHook(); //安裝鍵盤鉤子
  __declspec(dllexport)  BOOL APIENTRY EndHook();   //刪除鍵盤鉤子
  LRESULT WINAPI KeyProc(int nCode,WPARAM wparam,LPARAM lparam);
}


HHOOK     hHook=NULL;           //滑鼠鉤子函式控制代碼
HINSTANCE hInstance=NULL;       //DLL例項控制代碼
#pragma argsused
int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
{
        hInstance=hinst;
        return 1;
}
//---------------------------------------------------------------------------
__declspec(dllexport)  BOOL APIENTRY StartHook()
{


        hHook=SetWindowsHookEx(WH_KEYBOARD_LL,(HOOKPROC)KeyProc,hInstance,0);
        return (bool)hHook;
}


__declspec(dllexport)  BOOL APIENTRY EndHook()
{
        if(hHook&&UnhookWindowsHookEx(hHook))
           hHook=NULL;
        return (bool)hHook;
}


__declspec(dllexport) LRESULT WINAPI KeyProc(int nCode,WPARAM wparam,LPARAM lparam) {
        HWND hwnd;
        hwnd=FindWindow(NULL,"鍵盤鉤子測試");


        KBDLLHOOKSTRUCT *keyMSG=(KBDLLHOOKSTRUCT *)lparam;
        if(nCode==HC_ACTION && (WM_KEYDOWN == wparam || wparam == WM_SYSKEYDOWN))
        {


                DWORD dwMsg = 1;
                dwMsg += keyMSG->scanCode << 16;
                dwMsg += keyMSG->flags << 24;


                SendMessage(hwnd,WM_KEY_HOOK,(WPARAM)(dwMsg), lparam);
        }
        return CallNextHookEx(hHook,nCode,wparam,lparam); //繼續傳遞滑鼠訊息

}

測試程式中的程式碼:

標頭檔案中:自定義訊息型別和訊息對映函式

#define WM_KEY_HOOK    WM_USER+200  //自定義訊息

void __fastcall OnKeyHook(TMessage &Msg);

BEGIN_MESSAGE_MAP

        MESSAGE_HANDLER(WM_KEY_HOOK, TMessage, OnKeyHook);

END_MESSAGE_MAP(TForm);

原始碼中:

首先,宣告需要呼叫外部方法,用於安裝和解除安裝鉤子(按鈕事件觸發):

extern "C" {
 BOOL APIENTRY StartHook(); //安裝滑鼠鉤子
 BOOL APIENTRY EndHook();   //刪除鉤子
}

再實現OnKeyHook方法:

void __fastcall TForm1::OnKeyHook(TMessage &Msg)
{
        AnsiString  str;


        //獲取最前端視窗的控制代碼
        HWND hwnd = GetForegroundWindow();
        char windowTitle[50] = {0};
        GetWindowText(hwnd,windowTitle,sizeof(windowTitle));
        AnsiString result = AnsiString(windowTitle[0]);


        str += windowTitle;
        str += ":按下按鍵[" ;
        char key[20]={0};
        GetKeyNameText(Msg.WParam, key, 20);//根據滑鼠資訊獲取按鍵名
        str += key;
        
        str += "]";
        Memo1->Lines->Add(str);
}

原始碼雲盤地址:http://pan.baidu.com/s/1bn2Yi67