Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate a mouse movement

Tags:

How can I simulate a mouse event causing the pointer to move 500 pixels to the left, then click using C++. How would I do something like this?

like image 657
Josh Polk Avatar asked Sep 20 '11 22:09

Josh Polk


People also ask

How do you simulate a mouse event?

An easier and more standard way to simulate a mouse click would be directly using the event constructor to create an event and dispatch it. Though the MouseEvent. initMouseEvent() method is kept for backward compatibility, creating of a MouseEvent object should be done using the MouseEvent() constructor.

Is there an app that makes your mouse move?

Mouse Jiggler is a simple Windows app that, when activated, will move your cursor around. It has just two options: One that lets you see the cursor as it moves, and one that hides the cursor's movement.


1 Answers

Here's some modified Win32 code I had lying around:

#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0500

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <string.h>
#include <windows.h>


#define X 123
#define Y 123
#define SCREEN_WIDTH 1024
#define SCREEN_HEIGHT 800


void MouseSetup(INPUT *buffer)
{
    buffer->type = INPUT_MOUSE;
    buffer->mi.dx = (0 * (0xFFFF / SCREEN_WIDTH));
    buffer->mi.dy = (0 * (0xFFFF / SCREEN_HEIGHT));
    buffer->mi.mouseData = 0;
    buffer->mi.dwFlags = MOUSEEVENTF_ABSOLUTE;
    buffer->mi.time = 0;
    buffer->mi.dwExtraInfo = 0;
}


void MouseMoveAbsolute(INPUT *buffer, int x, int y)
{
    buffer->mi.dx = (x * (0xFFFF / SCREEN_WIDTH));
    buffer->mi.dy = (y * (0xFFFF / SCREEN_HEIGHT));
    buffer->mi.dwFlags = (MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE);

    SendInput(1, buffer, sizeof(INPUT));
}


void MouseClick(INPUT *buffer)
{
    buffer->mi.dwFlags = (MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN);
    SendInput(1, buffer, sizeof(INPUT));

    Sleep(10);

    buffer->mi.dwFlags = (MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTUP);
    SendInput(1, buffer, sizeof(INPUT));
}


int main(int argc, char *argv[])
{
    INPUT buffer[1];

    MouseSetup(&buffer);

    MouseMoveAbsolute(&buffer, X, Y);
    MouseClick(&buffer);

    return 0;
}

You'll need to call MouseSetup() to each INPUT buffer before you use it.

Resources

MSDN - SendInput()
MSDN - INPUT
MSDN - MOUSEINPUT

like image 144
Mateen Ulhaq Avatar answered Sep 19 '22 12:09

Mateen Ulhaq