Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"mouse_event" function - sending cursor to (slightly) wrong coordinates

The mouse_event function sends the cursor to slightly wrong coordinates (1-20 pixels off). The degree of how much it is "off" is based on a pattern I can't quite figure out.

Here is my code

int x, y;
int repeats = 1000;
int start = 0;
POINT pt;

for(int i=0; i<repeats; i+=10) //first loop, down right
{
    x = (65536 / 1920) * i - 1; //convert to absolute coordinates
    y = (65536 / 1080) * i - 1;
    mouse_event(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, x, y, 0, 0); //move
    GetCursorPos(&pt); //get cursor position
    if(pt.x != i){mouse_event(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, x, y, 0, 0);} //check if the position is wrong, and if so fix it.
    if(pt.y != i){mouse_event(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, x, y, 0, 0);}
    cout << "Try: " << i << ", " << i << "\tReal: " << pt.x << ", " << pt.y << "\tDiff: " << pt.x - i << ", " << pt.y - i << '\n';
}

    for(int i=repeats; i>0; i-=10) //second loop, up left
{
    x = (65536 / 1920) * i - 1;
    y = (65536 / 1080) * i - 1;
    mouse_event(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, x, y, 0, 0);
    GetCursorPos(&pt);
    if(pt.x != i){mouse_event(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, x, y, 0, 0);}
    if(pt.y != i){mouse_event(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, x, y, 0, 0);}
    cout << "Try: " << i << ", " << i << "\tReal: " << pt.x << ", " << pt.y << "\tDiff: " << pt.x - i << ", " << pt.y - i << '\n';
}

If this is run it results in the mouse moving down and right from the top left of the screen, then back up again. But the further down it goes, the more incorrect the mouse movements created by "mouse_event" end up being.

I move it, then record the current coordinates, then calculate the difference. The difference (the error in movements) increases the further down the screen I go. I've even tried to add an additional check which tests if the coordinates are off, then tries to move the mouse to the right spot again but it isn't working

Any idea why this might be?

Here is a log of the output for this program for convenience.

Output_Log.txt

It clearly shows that in the first loop (which moves the mouse down and right) the error increases, then on the second loop (which moves it back up and left again) the error decreases in the same way.

Any idea why this might be happening? It happens on more complex implementations as well in ways I can't quantify and which are unlike this one, so I think it must be within the mouse_event function itself or some feature I don't understand

Thanks in advance for any help

like image 930
Abraluna Avatar asked Nov 03 '22 21:11

Abraluna


1 Answers

I'd say it's due to using integer arithmetic to work out the pixels, try this:

x = (int)(65536.0 / 1920 * i - 1); //convert to absolute coordinates
y = (int)(65536.0 / 1080 * i - 1);
like image 130
joshuahealy Avatar answered Nov 12 '22 18:11

joshuahealy