1

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?

dbc
120k27 gold badges273 silver badges404 bronze badges
asked Mar 20, 2012 at 15:36
2
  • What does mouse_event look like? Commented Mar 20, 2012 at 15:43
  • some people just love to vote down. Commented Apr 20, 2012 at 13:25

1 Answer 1

2

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.

answered Mar 20, 2012 at 16:03
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.