【发布时间】:2023-04-01 02:15:01
【问题描述】:
如何以编程方式触发鼠标左键单击事件?
谢谢。
edit:事件不会直接在按钮上触发。我的目标是Windows平台。
【问题讨论】:
-
在哪个平台上?窗体? WPF?银光?网络表单(=html/javascript)?或者只是“windows”(低级)
如何以编程方式触发鼠标左键单击事件?
谢谢。
edit:事件不会直接在按钮上触发。我的目标是Windows平台。
【问题讨论】:
如果它在一个按钮上,你可以使用
button1.PerformClick();
否则,您可以查看this MSDN article,其中讨论了模拟鼠标(和键盘)输入。
此外,this project 也可以为您提供帮助。在幕后,它使用SendInput。
【讨论】:
https://web.archive.org/web/20140214230712/http://www.pinvoke.net/default.aspx/user32.sendinput
使用 Win32 API 发送输入。
更新:
由于我不再使用 Win32 API,因此当平台更改或网站不可用时,我不会更新此答案以使其正确。由于这个答案甚至不符合 Stackoverflow 标准(不包含答案本身,而是指向外部的、现已失效的资源的链接),因此没有必要给它任何分数或花费更多时间。
相反,看看 Stackoverflow 上的这个问题,我认为这是重复的:
【讨论】:
UINT 和INPUT[] 下放置了一行我看到没有像 UINT 这样的类虽然我可以将其更改为 UInt32 但我不知道 INPUT[] 的等效更改是什么工作
执行鼠标点击:
[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);
}
【讨论】:
Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Use.....\Debug\hprog.vshost.exe'. Additional information: A call to PInvoke function 'prog1!prog1.FrmBlah::mouse_event' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.