Nikil
Nikil

Reputation: 369

Simulate Mouse Click and Mouse Move in Windows 7 using C#

I have written a piece of code to simulate mouse click which is working fine in my Vista. But when I tested that in windows 7 its not generating the click event. Could some one please help? I am adding the code snippet below. Thanks, Nikil

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


[Flags]
        public enum MouseEventFlags
        {
            LEFTDOWN = 0x00000002,
            LEFTUP = 0x00000004,
            MIDDLEDOWN = 0x00000020,
            MIDDLEUP = 0x00000040,
            MOVE = 0x00000001,
            ABSOLUTE = 0x00008000,
            RIGHTDOWN = 0x00000008,
            RIGHTUP = 0x00000010
        }

System.Windows.Forms.Cursor.Hide();
System.Windows.Forms.Cursor.Position = new System.Drawing.Point(xinc + rct.Left, yinc + rct.Top);

int X = System.Windows.Forms.Cursor.Position.X;
int y = System.Windows.Forms.Cursor.Position.Y;

mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0);
mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0);


System.Windows.Forms.Cursor.Position = new System.Drawing.Point(0, 0);
System.Windows.Forms.Cursor.Show();

Upvotes: 1

Views: 8347

Answers (3)

Ohad Schneider
Ohad Schneider

Reputation: 38172

A trick that has worked for me is using SetCursorPos with the same coordinate before the mouse_event call. I've also just verified the following to work (on winforms):

    public static void LeftClick(int x, int y)
    {
        Cursor.Position = new System.Drawing.Point(x, y); //<= fails without this
        mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0);
        mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0);
    }

Upvotes: 0

John Petrak
John Petrak

Reputation: 2928

Not sure if this will help you, but have you looked at UI Automation? link text

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 942448

My crystal ball says you didn't just upgrade to Win7, you also got the 64-bit version. Previously you had the 32-bit version of Vista. Your mouse_event() declaration is wrong. The last argument is IntPtr, not int.

How did the ball do?

Upvotes: 9

Related Questions