/***************************************************************** clearMyHook* Inputs:* HWND hWnd: Window whose hook is to be cleared* Result: BOOL* TRUE if the hook is properly unhooked* FALSE if you gave the wrong parameter* Effect:* Removes the hook that has been set.****************************************************************/__declspec(dllexport) BOOL clearMyHook(HWND hWnd) { if(hWnd != hWndServer) return FALSE; BOOL unhooked = UnhookWindowsHookEx(hook); if(unhooked) hWndServer = NULL; return unhooked; }/***************************************************************** msghook* Inputs:* int nCode: Code value* WPARAM wParam: parameter* LPARAM lParam: parameter* Result: LRESULT** Effect:* If the message is a mouse-move message, posts it back to* the server window with the mouse coordinates* Notes:* This must be a CALLBACK function or it will not work!****************************************************************/ static LRESULT CALLBACK msghook(int nCode, WPARAM wParam, LPARAM lParam) { // If the value of nCode is < 0, just pass it on and return 0 // this is required by the specification of hook handlers if(nCode < 0) { /* pass it on */ CallNextHookEx(hook, nCode, wParam, lParam); return 0; } /* pass it on */ // Read the documentation to discover what WPARAM and LPARAM // mean. For a WH_MESSAGE hook, LPARAM is specified as being // a pointer to a MSG structure, so the code below makes that // structure available LPMSG msg = (LPMSG)lParam; // If it is a mouse-move message, either in the client area or // the non-client area, we want to notify the parent that it has // occurred. Note the use of PostMessage instead of SendMessage if(msg->message == WM_MOUSEMOVE || msg->message == WM_NCMOUSEMOVE) PostMessage(hWndServer, UWM_MOUSEMOVE, 0, 0); // Pass the message on to the next hook return CallNextHookEx(hook, nCode, wParam, lParam); } // msghookThe server application
在頭文件中,將下面的增加到類的protected段:
afx_msg LRESULT OnMyMouseMove(WPARAM,LPARAM);在application 文件中, 增加以下代碼到文件前部。
UINT UWM_MOUSEMOVE = ::RegisterWindowMessage(UWM_MOUSEMOVE_MSG);在 MESSAGE_MAP, 增加以下代碼
//{AFX_MSG comments:
ON_REGISTERED_MESSAGE(UWM_MOUSEMOVE, OnMyMouseMove)In your application file, add the following function:
LRESULT CMyClass::OnMyMouseMove(WPARAM, LPARAM) { // ...do stuff here return 0; } 上面是我寫的一個小程序。既然我為了鉤子花了n+1st 時間,我干脆給它一個好的用戶界面。 貓在窗口之內盯著老鼠。小心! 當老鼠足夠接近貓時並且它將捉住老鼠!
你可以下載這個項目並建立它。 真正的關鍵是DLL 子工程項目; 其他的都不過是陪襯。有幾個其它的技術被用在這個例子裡,包括各種各樣的圖畫技術, ClipCursor 和 SetCapture的用法,區域選擇、屏幕更新等等。,因此除了展示鉤子函數的使用以外,對初級程序員掌握窗口樣式設計編程也有一些價值。