如何在C#中以编程方式触发鼠标左键单击?

时间:2010-04-29 11:46:08

标签: c# click mouse

如何以编程方式触发鼠标左键单击事件?

感谢。

编辑:事件不是直接在按钮上触发的。我的目标是Windows平台。

3 个答案:

答案 0 :(得分:8)

如果它在按钮上,则可以使用

button1.PerformClick();

否则,您可以查看讨论模拟鼠标(和键盘)输入的this MSDN article

此外,this project也可以为您提供帮助。在封面下,它使用SendInput

答案 1 :(得分:8)

要执行鼠标单击:

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

将光标移动到所需位置:

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

        public static void MoveCursorToPoint(int x, int y)
        {
            SetCursorPos(x, y);
        }

答案 2 :(得分:1)

https://web.archive.org/web/20140214230712/http://www.pinvoke.net/default.aspx/user32.sendinput

使用Win32 API发送输入。

<强>更新

由于我不再使用Win32 API,因此当平台更改或网站不可用时,我不会将此答案更新为正确。由于这个答案甚至不符合Stackoverflow标准(不包含答案本身,而是指向外部,现在已经不存在的资源的链接),因此没有必要给它任何积分或花费更多时间。

相反,请看看Stackoverflow上的这个问题,我认为这是重复的:

How to simulate Mouse Click in C#?