C# Clicking on a certain point on the screen
I am trying to perform a mouse click through c#. I used the mouse_event function to do it.
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
[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);
I tried two methods :
Moving the mouse to the point and clicking it :
Cursor.Position = new Point(100, 100);
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
Passing the x, y of the desired click to the function :
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP,100, 100, 0, 0)开发者_开发问答;
Either way, I'm this weird error :
Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users\or\Documents\Visual Studio 2010\Projects\ProjectName\ProjectName\bin\Debug\ProjectName.vshost.exe'. Additional Information: A call to PInvoke function 'ProjectName!ProjectName.MainForm::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.
Any ideas on a solution?
I would suggest you use the following p/invoke signature
private const uint MOUSEEVENTF_LEFTDOWN = 0x02;
private const uint MOUSEEVENTF_LEFTUP = 0x04;
[DllImport("user32.dll")]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, IntPtr dwExtraInfo);
Note, that while mouse_event
is convenient, it has been superseded by SendInput. You can find a reasonable p/invoke declaration for SendInput and the Input structure at the following URL.
http://www.pinvoke.net/default.aspx/user32.SendInput
You have obviously got this code from legacy VB6 code. long is 64-bit in .NET and C#, unlike VB6 where it is 32-bit.
Switch from long to int, and it should be okay.
edit: I was a little fast: dwExtraInfo should be of type IntPtr.
精彩评论