For example, I want to simulate a mouse click at a specific position in a window, but I don't want my real cursor to move or do anything. Is there a possible solution ?
CodePudding user response:
I wrote a mouse operation sample of SendInput, hoping to help you. For more mouse operations, please refer to the definition here
#include <windows.h>
#include <iostream>
void mouseEvent(int x, int y,DWORD dwFlags) {
MOUSEINPUT mi = { 0 };//Create a mouse structure variable
mi.dwFlags = dwFlags;
//Set the flags to move and absolute position.
//The absolute position means that the mouse will be set with the upper left corner as 0, 0, and dx, dy as the coordinate values (the range is 0~65535). If there is no such flag, it is the relative position of moving dx and dy from the last mouse position as the starting point.
//Next, we need to correspond dx and dy to screen coordinates. The MOUSEEVENTF_VIRTUALDESK flag seems to do the job, but it doesn't work as expected, so I don't know how to use this parameter.
//Then we can complete the normalization task by ourselves, that is, normalize the coordinates of (0~65535) to the value range of (0~screen width, 0~screen height).
//First get the screen width and height
int cx_screen = ::GetSystemMetrics(SM_CXSCREEN);
int cy_screen = ::GetSystemMetrics(SM_CYSCREEN);
//Perform normalization processing and use float type to ensure accuracy
float per_x = 65535.0f / cx_screen;
float per_y = 65535.0f / cy_screen;
//Rounding with the ceilf function
mi.dx = (long)ceilf(x * per_x);
mi.dy = (long)ceilf(y * per_y);
//Set this structure to the SendInput function
INPUT input{};
input.type = INPUT_MOUSE;
input.mi = mi;
SendInput(1, &input, sizeof(INPUT));
}
int main()
{
//std::cout << "Hello World!\n";
mouseEvent(10, 10, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE);
mouseEvent(10, 10, MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_ABSOLUTE);
mouseEvent(10, 10, MOUSEEVENTF_RIGHTUP | MOUSEEVENTF_ABSOLUTE);
}
CodePudding user response:
If you want to send inputs to the active window you can do it by following this article.
It uses InputSimulator to send inputs to active windows. It is available as a Nuget package too.
Edit: If you want to send mouse events without moving your own cursor, what you could try is running your target program and the C# automation program inside a virtual machine, that way you can have 2 mouse cursors (one in your main OS, and the other in the automated OS)