一、任務要求。
需要我們編寫一個程序能夠自動的進行某些鼠標點擊的操作。比如某個客戶端,我們利用程序,可以自動點擊操作。
二、需求分析。
為了實現這種要求,我們必須首先獲得需要操作窗口的句柄。其次是點擊的位置。
1.獲取窗口的句柄。
我們需要明確,我們在獲得窗口的句柄時,要明確我們窗口是不是頂級窗口。因為我們獲取窗口的函數(FindWindow()),是在頂層窗口中查找的。或者利用其它API從最頂層的位置向下索引。這些都要根據我們要操作窗口的位置來決定的。在本程序中,我們是利用頂層窗口的句柄,然后利用距離頂層窗口起始點的相對位置來進行模擬鼠標點擊。
2.點擊位置。
點擊位置的確定需要注意的一點是,我們用按鍵精靈的抓抓工具時,上面的相對位置是客戶區的相對位置,並不是距離頂層窗口起始點的相對位置。
三、工具
1.按鍵精靈的抓抓工具、vs2017。
四、代碼實現

1 int mousemove(int x, int y) { 2 ::SetCursorPos(x, y); 3 mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); 4 return 0; 5 }

1 bool mouse_down(string titlename, int position_x, int position_y) { 2 HWND hd_desk = GetDesktopWindow(); 3 4 HWND hd = GetWindow(hd_desk, GW_CHILD); //得到屏幕上第一個子窗口 5 char s[200] = { 0 }; 6 std::cout << "enter in" << std::endl; 7 while (hd != NULL) //循環得到所有的子窗口 8 { 9 memset(s, 0, 200); 10 GetWindowText(hd, s, 200); 11 //GetClassName(hd, s, 200); 12 string b(&s[0], &s[strlen(s)]); 13 if (b ==titlename) { //Notepad 14 RECT rect; 15 GetWindowRect(hd, &rect); 16 int w = rect.right - rect.left, h = rect.bottom - rect.top; 17 std::cout << "寬:" << w << " " << "高:" << h << std::endl; 18 std::cout << "rect.left:" << rect.left << " " << "rect.top:" << rect.top << std::endl; 19 //SetWindowPos(hd, HWND_TOPMOST, rect.left, rect.top, w, h, NULL); 20 //int bool_break = TRUE; 21 int num = 0; 22 while (TRUE) { 23 int mouse_x = rect.left + position_x; 24 int mouse_y = rect.top + position_y; 25 mousemove(mouse_x, mouse_y); 26 num++; 27 if (NULL == FindWindow(NULL, s)||num==10) { 28 break; 29 } 30 } 31 std::cout << "find it" << std::endl; 32 33 34 35 36 //模擬點擊事件 37 38 //mousemove(rect.left + 180, rect.top + 210 + 240); 39 //::SetCursorPos(lpPoint.x, lpPoint.y); 40 //SetWindowPos(hd, HWND_NOTOPMOST, rect.left, rect.top, w, h, NULL); 41 break; 42 } 43 hd = GetNextWindow(hd, GW_HWNDNEXT); 44 } 45 }
五、代碼分析
1.模擬點擊。
利用的是Windows API。首先移動鼠標到需要點擊的位置,然后,調用點擊函數。
2.點擊實現。
首先參數是:1.窗口的標題,用抓抓工具可以獲得。2.相對位置x,3.相對位置Y。
需要注意的一點是,我這個功能是關閉某個窗口的操作,所以用是否是NULL來確定是否完成點擊。