获取窗口句柄模拟鼠标点击

一、任务要求。

  需要我们编写一个程序能够自动的进行某些鼠标点击的操作。比如某个客户端,我们利用程序,可以自动点击操作。

二、需求分析。

  为了实现这种要求,我们必须首先获得需要操作窗口的句柄。其次是点击的位置。

  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来确定是否完成点击。

posted @ 2018-09-20 20:52  昔时  阅读(5470)  评论(0编辑  收藏  举报