How could I programmatically trigger a left-click event on the mouse?
Thanks.
edit: the event is not triggered directly on a button. I'm aiming for the Windows platform.
-
3In which platform? Winforms? WPF? Silverlight? webforms(=html/javascript)? Or just "windows" (low level)Marc Gravell– Marc Gravell2010年04月29日 11:49:38 +00:00Commented Apr 29, 2010 at 11:49
-
Possible duplicate of How to simulate Mouse Click in C#?Alex– Alex2017年05月16日 11:46:35 +00:00Commented May 16, 2017 at 11:46
3 Answers 3
To perform a mouse click:
[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);
}
To move the cursor where you want:
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);
public static void MoveCursorToPoint(int x, int y)
{
SetCursorPos(x, y);
}
4 Comments
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.int not long. And the last parameter is a pointer. void mouse_event(uint dwFlags, int dx, int dy, uint dwData, UIntPtr dwExtraInfo); I'll see if I can edit the answer.If it's right on a button, you can use
button1.PerformClick();
Otherwise, you can check out this MSDN article which discusses simulating mouse (and keyboard) input.
Additionally, this project may be able to help you out as well. Under the covers, it uses SendInput.
1 Comment
https://web.archive.org/web/20140214230712/http://www.pinvoke.net/default.aspx/user32.sendinput
Use the Win32 API to send input.
Update:
Since I no longer work with Win32 API, I will not update this answer to be correct when the platform changes or websites become unavailable. Since this answer doesn't even conform to Stackoverflow standards (does not contain the answer itself, but rather a link to an external, now defunct resource), there's no point giving it any points or spending any more time on it.
Instead, take a look at this question on Stackoverflow, which I think is a duplicate:
3 Comments
UINT and under INPUT[] I see there is no such class as UINT though I can change that to UInt32 But I don't what the equivalent change would be to INPUT[] to make it work