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

我怎样才能以编程方式触发鼠标左键单击事件?

谢谢。

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

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

使用Win32 API发送输入。

更新:

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

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

如何在C#中模拟鼠标点击?

如果它在按钮上是正确的,您可以使用

 button1.PerformClick(); 

否则,您可以查看这篇讨论模拟鼠标(和键盘)输入的MSDN文章 。

此外, 该项目也可以帮助您。 在封面下,它使用SendInput 。

要执行鼠标单击:

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