mouse_event实现鼠标拖动

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值