开发者

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();


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?


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


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);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜