- 1 year ago
How to simulate a mouse click and drag?
Comment
1 / 1
To simulate a mouse click and drag in C#, you can use the SendInput
function from the user32.dll
library. Here's an example of how you can do it:
csharpusing System;
using System.Runtime.InteropServices;
public class MouseSimulator
{
// Import the necessary functions from user32.dll
[DllImport("user32.dll", SetLastError = true)]
private static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, UIntPtr dwExtraInfo);
[DllImport("user32.dll", SetLastError = true)]
private static extern void SendInput(int nInputs, INPUT[] pInputs, int cbSize);
[StructLayout(LayoutKind.Sequential)]
struct INPUT
{
public uint type;
public MOUSEINPUT mi;
}
[StructLayout(LayoutKind.Sequential)]
struct MOUSEINPUT
{
public int dx;
public int dy;
public uint mouseData;
public uint dwFlags;
public uint time;
public UIntPtr dwExtraInfo;
}
private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
private const int MOUSEEVENTF_LEFTUP = 0x0004;
private const int MOUSEEVENTF_MOVE = 0x0001;
public static void SimulateMouseClickAndDrag(int startX, int startY, int endX, int endY)
{
// Move the mouse to the starting position
MoveMouse(startX, startY);
// Press the left mouse button down
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, UIntPtr.Zero);
// Move the mouse to the end position
MoveMouse(endX, endY);
// Release the left mouse button
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, UIntPtr.Zero);
}
private static void MoveMouse(int x, int y)
{
// Create an INPUT structure for mouse movement
INPUT[] input = new INPUT[1];
input[0].type = 0; // INPUT_MOUSE
input[0].mi.dx = x;
input[0].mi.dy = y;
input[0].mi.dwFlags = MOUSEEVENTF_MOVE;
// Send the mouse movement input
SendInput(1, input, Marshal.SizeOf(typeof(INPUT)));
}
}
You can then use the SimulateMouseClickAndDrag
method to simulate a mouse click and drag by specifying the starting and ending coordinates of the movement.
csharpint startX = 100;
int startY = 100;
int endX = 200;
int endY = 200;
MouseSimulator.SimulateMouseClickAndDrag(startX, startY, endX, endY);
Please note that simulating user input in this way may have legal and ethical implications, and should be used responsibly and in compliance with applicable laws and guidelines.