Pedro77
Pedro77

Reputation: 5294

Code for mouse click

I'm trying to make a click at desktop through code, so I did that:

    public static void MouseLeftClick(Point pos)
    {
        System.Windows.Forms.Cursor.Position = pos;
        mouse_event(MOUSEEVENTF_LEFTDOWN, pos.X, pos.Y, 0, 0);
        mouse_event(MOUSEEVENTF_LEFTUP, pos.X, pos.Y, 0, 0);
    }

I realize that it only works if I add the System.Windows.Forms.Cursor.Position = pos; Why? mouse_event x,y parameters are useless?

Upvotes: 1

Views: 7022

Answers (1)

ken2k
ken2k

Reputation: 49013

Have you read the description of the mouse_event function?

If for instance only RIGHTDOWN is used, X and Y parameters don't represent the coordinates where the mouse is set..

Here's how you could deal with mouse_event:

[DllImport("user32.dll")]
private static extern void mouse_event(MouseEventFlags dwFlags, uint dx, uint dy, uint dwData, UIntPtr dwExtraInfo);

...

// Converts into pixels
uint x = (uint)(pos.X * 65535 / Screen.PrimaryScreen.Bounds.Width);
uint y = (uint)(pos.Y * 65535 / Screen.PrimaryScreen.Bounds.Height);

// Moves the mouse (absolute)
mouse_event(MouseEventFlags.MOVE | MouseEventFlags.ABSOLUTE, x, y, 0, UIntPtr.Zero);

// Now button down
mouse_event(MouseEventFlags.RIGHTDOWN, 0, 0, 0, UIntPtr.Zero);
mouse_event(MouseEventFlags.RIGHTUP, 0, 0, 0, UIntPtr.Zero);

Of course, setting the cursor position is much more simple than using mouse_event to tell that your mouse has moved.

Btw, this function has been superseded. Use SendInput instead.

Upvotes: 2

Related Questions