Sam
Sam

Reputation: 41

SendInput moves the cursor when I try to perform a mouse click

I'm trying to simulate a left mouse button click with SendInput, and it works but also moves the cursor to the upper left corner of the screen (0,0) and I can't figure it out why.

(I'm using the same structures to move the cursor (relatively and absolutely) and that's working.)

private static void Send(INPUT input)
{
  SendInput(1, ref input, Marshal.SizeOf(new INPUT()));
}
private static void MouseAction(MouseFlags mf)
{
  INPUT aInput = new INPUT();
  aInput.type = InputType.INPUT_MOUSE;
  aInput.mkhi.mi.dwFlags = mf;

  Send(aInput);
}

// Performs a LeftClick but moves the cursor to (0.0)
public static void LeftClick()
{
  MouseAction(MouseFlags.MOUSEEVENTF_LEFTDOWN | MouseFlags.MOUSEEVENTF_LEFTUP);
}

The result is the same when I fill out all of the structure members. The full INPUT definition:

[StructLayout(LayoutKind.Sequential)]
struct INPUT
{
    public InputType type;
    public MouseKeyboardHardwareUnion mkhi;
}
[StructLayout(LayoutKind.Explicit)]
struct MouseKeyboardHardwareUnion
{
    [FieldOffset(0)]
    public MOUSEINPUT mi;

    [FieldOffset(0)]
    public KEYBDINPUT ki;
}
[StructLayout(LayoutKind.Sequential)]
struct MOUSEINPUT
{
    public int dx;
    public int dy;
    public uint mouseData;
    public MouseFlags dwFlags;
    public uint time;
    public IntPtr dwExtraInfo;
}
// Not relevant
[StructLayout(LayoutKind.Sequential)]
struct KEYBDINPUT
{
    public KeyboardVirtual wVk;
    public ushort wScan;
    public KeyboardFlags dwFlags;
    public uint time;
    public IntPtr dwExtraInfo;
}

Filling out the MOUSEINPUT's dx and dy fields with the cursor's current position doesn't seem to solve the problem either.

Upvotes: 1

Views: 1661

Answers (2)

Sam
Sam

Reputation: 41

I figured it out, the problem wasn't with the INPUT structure, I called the LeftClick() function inside an EventArgs constructor. After I moved it outside it works just fine.

Upvotes: 1

Maximilian Schier
Maximilian Schier

Reputation: 1679

First, it would really help if you would show the definition of your INPUT structure.

Second, in case your INPUT structure contains the X and Y coordinate, set them using:

aInput.somethingX = Cursor.Position.X;
aInput.somethingY = Cursor.Position.Y;

because otherwise it will of course reset your cursor position.

Third, just search on google and stackoverflow and you find plenty of people that already asked this and got helpful answers like this.

Upvotes: 2

Related Questions