What should I do to make this code work in VS 2010?

I used this code manually to simulate a mouse click on a system using code.

using System; using System.Windows.Forms; using System.Runtime.InteropServices; public class Form1 : Form { [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 Form1() { } public void DoMouseClick() { //Call the imported function with the cursor current position int X = Cursor.Position.X; int Y = Cursor.Position.Y; mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0); } //...other code needed for the application } 

But now I am using VS 2010 and Windows 7, and I am getting an error while executing this code now

 mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0); 

So, any suggestions for this ...

The error I am encountering is:

PInvokeStackImbalance detected

Calling PInvoke 'ClickingApp! ClickingApp.Form1 :: mouse_event 'has an unbalanced stack. This is likely due to the fact that the PInvoke managed signature does not match the unmanaged target signature. Verify that the calling agreement and PInvoke signature settings match the target unmanaged signature.

+4
source share
1 answer

The problem is that the P / Invoke signature is trying to do this.

 [DllImport("user32.dll")] static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, UIntPtr dwExtraInfo); 

DWORD is 32 bits and C # long is 64 bits

You have also noticed that you are specifying a calling convention, it is better not to specify it when using P / Invoke for the Windows API, or you can use CallingConvention.Winapi, an incorrect calling convention is usually the cause of stack imbalance.

+5
source

Source: https://habr.com/ru/post/1315113/


All Articles