如何在C++中模拟鼠标光标的移动

How to simulate mouse cursor movement in C++

本文关键字:鼠标 光标 移动 模拟 C++      更新时间:2023-10-16

我正在业余时间创建一个程序,并试图模拟鼠标光标的移动。

我试着让它在我启动程序时将光标从[x,y]移动到[0,0](这是我屏幕的左上角(。

有没有办法在不传送的情况下做到这一点?

以下是到目前为止我的鼠标光标移动程序的内容:

POINT p;
GetCursorPos( &p );
double mouseX = p.x;
double mouseY = p.y;
SetCursorPos(0, 0);

有没有办法真正看到我的鼠标被移动,而不是立即传送到[0,0]?

您需要一次一点地逐步推进鼠标。例如,考虑以下伪代码函数:

def moveMouse (endX, endY, stepCount, stepDelay):
GetCurrentPosTo(startX, startY);
for step = 1 to stepCount
currX = startX + (endX - startX) * step / stepCount
currY = startY + (endY - startY) * step / stepCount
SetCurrentPosFrom(currX, currY)
DelayFor(stepDelay)
endfor
enddef

这将计算当前位置(在循环中(,作为从(startX, startY)(endX, endY)的行程的一部分,并根据您希望走的步数进行调整。

因此,使用100的stepCount和10毫秒的stepDelay,鼠标光标将在一秒钟内平稳移动。

可能还有其他的可能性,例如以特定的速度移动光标而不是花费特定的时间,或者指定最小速度和最大时间来组合这两种方法。

我将把它作为额外的练习。只需说,它将涉及相同的方法,即一次移动光标一点,而不仅仅是立即将其位置设置为最终值。

这是我在网上的小混合物!

它使鼠标从屏幕中心向外旋转,而且相当流畅,呈阿基米德螺旋形。你也可以在循环中搞砸数学,特别是"cos(("answers"sin(("函数,让它做不同的动作。仅用于教育目的。

享受:(

#include <Windows.h>
#include <iostream>
void moveMouse(int x, int y){
int count = 800;
int movex, movey;
float angle = 0.0f;
// set mouse at center screen
SetCursorPos(x/2, y/2); 
// begin spiral! :)
for(int i = 0; i <= count; i++){
angle = .3 * i;
movex = (angle * cos(angle) * 2) + x/2;
movey = (angle * sin(angle) * 2) + y/2;
SetCursorPos(movex, movey);
Sleep(1);
}
}
int main(){
int Height = GetSystemMetrics(SM_CYSCREEN);
int Width = GetSystemMetrics(SM_CXSCREEN);
moveMouse(Width,Height);
return 0;
}

您将不得不多次调用SetCursorPos,坐标首先接近您的点,然后逐渐接近(0,0(。如果没有一些故意的拖延,它无论如何都会立即发生,所以请记住这一点。

试试我用来调试输入的代码。。我把它放在它每帧运行的地方。获取鼠标位置,然后设置鼠标位置。你的鼠标不应该移动,或者数学错误。。

{
POINT       pos;
GetCursorPos(&pos);
INPUT input[1];
memset(&input, 0, sizeof(input));
int left    = GetSystemMetrics(SM_XVIRTUALSCREEN);
int top     = GetSystemMetrics(SM_YVIRTUALSCREEN);
int width   = GetSystemMetrics(SM_CXVIRTUALSCREEN);
int heigth  = GetSystemMetrics(SM_CYVIRTUALSCREEN);
// 0x1000 because 0 to 0xffff is not 65535, its 65536.
// we add 0.5f to the location to put us in the center of the pixel. to avoid rounding errors.  Take it out and your mouse will move up and to the left.
POINT Desired;
Desired.x = ((float)(pos.x - left ) + 0.5f) * (float) (0x10000) / (float) (width);
Desired.y = ((float)(pos.y - top) + 0.5f) * (float) (0x10000) / (float) (heigth);
// move to new location
input[0].type           = INPUT_MOUSE;
input[0].mi.dx          = Desired.x;
input[0].mi.dy          = Desired.y;
input[0].mi.mouseData   = 0;
input[0].mi.dwFlags     = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE_NOCOALESCE | MOUSEEVENTF_MOVE | MOUSEEVENTF_VIRTUALDESK;
input[0].mi.time        = 0;
SendInput(1, &input[0], sizeof(INPUT));
}