C++小工具之得到鼠标位置并模拟点击

检测鼠标左键被按下:

    KEY_DOWN(VK_LBUTTON)

得到鼠标按下时坐标:

    POINT p;
    GetCursorPos(&p);
    cout << " x position:" << p.x << " y position: " << p.y << endl;

设置模拟点击的位置并模拟点击:

    SetCursorPos(atoi(argv[1]), atoi(argv[2]));
    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);

完整程序:

#include
#include

#define KEY_DOWN(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0)

using namespace std;
int main(int argc, char ** argv) 
{
    if (argc != 4)
    {
        cout << "Command Usage: MouseDetection.exe x_position y_position time(s).";
    }

    POINT p;
    while (true) 
    {
        #if 0
          //Get current cursor position.
          if (KEY_DOWN(VK_LBUTTON))
          { 
            GetCursorPos(&p);
            cout << " x position:" << p.x << " y position: " << p.y << endl;
            Sleep(10); //set time interval.
          }
        #endif

        static INT64 clickCount = 0;
        cout << clickCount ++ << " x position:" << argv[1] << " y position: " << argv[2] << endl;

        SetCursorPos(atoi(argv[1]), atoi(argv[2]));
        mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);

        //Click every 5 minutes.
        Sleep(1000 * atoi(argv[3]));

        //Quit the loop or Ctrl + C;
        if (KEY_DOWN('Q')) {
            return 0;
        }
    }

    return 0;
}

参考:

 https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate
 https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getcursorpos
 https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setcursorpos
 https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mouse_event
 https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-keybd_event

 

你可能感兴趣的:(小工具)