How do you simulate Mouse Click in C#?

后端 未结 7 1171
长情又很酷
长情又很酷 2020-11-22 05:34

How do you simulate Mouse clicks in C# winforms applications?

7条回答
  •  时光说笑
    2020-11-22 06:16

    I have tried the code that Marcos posted and it didn't worked for me. Whatever i was given to the Y coordinate the cursor didn't moved on Y axis. The code below will work if you want the position of the cursor relative to the left-up corner of your desktop, not relative to your application.

        [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_MOVE = 0x0001;
    
        public void DoMouseClick()
        {
            X = Cursor.Position.X;
            Y = Cursor.Position.Y;
    
            //move to coordinates
            pt = (Point)pc.ConvertFromString(X + "," + Y);
            Cursor.Position = pt;       
    
            //perform click            
            mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
            mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
        }
    

    I only use mouse_event function to actually perform the click. You can give X and Y what coordinates you want, i used values from textbox:

                X = Convert.ToInt32(tbX.Text);
                Y = Convert.ToInt32(tbY.Text);
    

提交回复
热议问题