views:

308

answers:

3

Hi.

How could I programatically trigger a left-click event on the mouse?

Thanks.

edit: the event is not triggered directly on a button. I'm aiming for the Windows platform.

+6  A: 

If it's right on a button, you can use

button1.PerformClick();

Otherwise, you can check out this MSDN article which discusses simulating mouse (and keyboard) input.

Additionally, this project may be able to help you out as well. Under the covers, it uses SendInput.

SB
+1  A: 

http://www.pinvoke.net/default.aspx/user32.sendinput

use Win32 API to send input.

Alexander
+1  A: 

To perform a mouse click:

 [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);

        private const int MOUSEEVENTF_LEFTDOWN = 0x02;
        private const int MOUSEEVENTF_LEFTUP = 0x04;
        private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
        private const int MOUSEEVENTF_RIGHTUP = 0x10;

        public static void DoMouseClick()
        {
            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
        }

To move the cursor where you want:

[DllImport("user32.dll")]
        static extern bool SetCursorPos(int X, int Y);

        public static void MoveCursorToPoint(int x, int y)
        {
            SetCursorPos(x, y);
        }
JohnForDummies
I saw this one, tried it, but the mouse_event function is obsolete. I'm trying to do the same thing with SendInput now.
Andrei