SendInput doesn’t perform click mouse button unless I move cursor

There are a few things you should consider when using the SendInput function.

If you do not specify the MOUSEEVENTF_ABSOLUTE flag then dx and dy (MouseInputData structure) are relative coordinates to the current mouse position. If you do specify MOUSEEVENTF_ABSOLUTE then dx and dy are absolute coordinates between 0 and 65535. So if your x and y coordinates are screen coordinates you should use the following function to calculate dx and dy:

enum SystemMetric
{
  SM_CXSCREEN = 0,
  SM_CYSCREEN = 1,
}

[DllImport("user32.dll")]
static extern int GetSystemMetrics(SystemMetric smIndex);

int CalculateAbsoluteCoordinateX(int x)
{
  return (x * 65536) / GetSystemMetrics(SystemMetric.SM_CXSCREEN);
}

int CalculateAbsoluteCoordinateY(int y)
{
  return (y * 65536) / GetSystemMetrics(SystemMetric.SM_CYSCREEN);
}

Furthermore before you send the MOUSEDOWN and MOUSEUP events to via SendInput you have to move the mouse to the control you want to click on:

public static void ClickLeftMouseButton(int x, int y)
{
  INPUT mouseInput = new INPUT();
  mouseInput.type = SendInputEventType.InputMouse;
  mouseInput.mkhi.mi.dx = CalculateAbsoluteCoordinateX(x);
  mouseInput.mkhi.mi.dy = CalculateAbsoluteCoordinateY(y);
  mouseInput.mkhi.mi.mouseData = 0;                     


  mouseInput.mkhi.mi.dwFlags = MouseEventFlags.MOUSEEVENTF_MOVE |MouseEventFlags.MOUSEEVENTF_ABSOLUTE;
  SendInput(1, ref mouseInput, Marshal.SizeOf(new INPUT()));

  mouseInput.mkhi.mi.dwFlags = MouseEventFlags.MOUSEEVENTF_LEFTDOWN;
  SendInput(1, ref mouseInput, Marshal.SizeOf(new INPUT()));

  mouseInput.mkhi.mi.dwFlags = MouseEventFlags.MOUSEEVENTF_LEFTUP;
  SendInput(1, ref mouseInput, Marshal.SizeOf(new INPUT()));            
} 

The above code assumes that x and y are screen pixel coordinates. You can calculate those coordinates for a button (the target) on a winform by using the following code:

 Point screenCoordsCentre=
button1.PointToScreen(new Point(button1.Width/2, button1.Height/2));

Hope, this helps.

Leave a Comment