c++环境通过mouse_event实现windows系统中鼠标的精确移动。
核心移动代码:
//选中mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); //移动mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, newpos[0], //x偏移后的值,偏移后的值若大于65535自动取65535 newpos[1], //y偏移后的值 0, 0); //释放按键mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
移动鼠标功能实现测试代码:
#include <windows.h>#include <stdio.h>#include<iostream>#pragma comment(lib, "user32.lib") using namespace std;void main(){ //获取鼠标信息 int aMouseInfo[3]; SystemParametersInfo(SPI_GETMOUSE, // Get mouse information 0, // Not used &aMouseInfo, // Holds mouse information 0); // Not used cout << "threshold value1 is " << aMouseInfo[0] << " " << "threshold value2 is" << aMouseInfo[1] << " " << "mouse acceleration is " << aMouseInfo[2] << endl; int mousespeed; SystemParametersInfo(SPI_GETMOUSESPEED, 0, &mousespeed, 0); cout << "mousespeed is " << mousespeed << endl; //获取屏幕分辨率 int screenwidth, screenhight; screenwidth = GetSystemMetrics(SM_CXSCREEN); screenhight = GetSystemMetrics(SM_CYSCREEN); cout << "屏幕分辨率" << screenwidth << " " << screenhight << endl; //获取当前坐标位置 POINT pNow = { 0, 0 }; GetCursorPos(&pNow); cout << "当前坐标:" << pNow.x << ", " << pNow.y << endl; int move_x, move_y; cout << "输入X偏移" << endl; cin >> move_x; cout << "输入Y偏移" << endl; cin >> move_y; //鼠标坐标系[(0,65535),(0,65535)] //屏幕坐标转换到鼠标坐标 int newpos[2]; newpos[0] = (move_x+ pNow.x+1) * 65536 / screenwidth-1; newpos[1] = (move_y+ pNow.y+1) * 65536 / screenhight-1; mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, newpos[0], //x偏移后的值,偏移后的值若大于65535自动取65535 newpos[1], //y偏移后的值 0, 0); //获取偏移后坐标 POINT pNew = { 0, 0 }; GetCursorPos(&pNew); cout <<" 新坐标: " << pNew.x << ", " << pNew.y << endl; cout << "X偏移量:" << pNew.x - pNow.x << endl; cout << "Y偏移量:" << pNew.y - pNow.y << endl; Sleep(500); }
参考:
https://docs.microsoft.com/zh-cn/windows/win32/api/winuser/nf-winuser-mouse_event
https://docs.microsoft.com/zh-cn/windows/win32/api/winuser/nf-winuser-systemparametersinfoa