Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# -- PInvokeStackImbalance detected on a well documented function?

Tags:

c#

pinvoke

Here is my code for a ClickMouse() function:

    [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 long MOUSEEVENTF_LEFTDOWN = 0x02;
    private const long MOUSEEVENTF_LEFTUP = 0x04;
    private const long MOUSEEVENTF_RIGHTDOWN = 0x08;
    private const long MOUSEEVENTF_RIGHTUP = 0x10;
    private void ClickMouse()
    {
        long X = Cursor.Position.X;
        long Y = Cursor.Position.Y;
        mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);

    }

For some reason, when my program comes to this code, it throws this error message:

PInvokeStackImbalance was detected Message: A call to PInvoke function 'WindowsFormsApplication1!WindowsFormsApplication1.Form1::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.

Please help?

like image 594
Aaron Hammond Avatar asked May 31 '10 13:05

Aaron Hammond


3 Answers

Looks like your DllImport declaration is wrong. In particular the use of Int64 (longs), instead of UInt32.

Here's some detail from the PInvoke reference:
http://www.pinvoke.net/default.aspx/user32.mouse_event

[DllImport("user32.dll")]
static extern void mouse_event(uint dwFlags, uint dx, uint dy, 
                               uint dwData,UIntPtr dwExtraInfo);
like image 184
Scott Weinstein Avatar answered Oct 28 '22 07:10

Scott Weinstein


I found this declaration

[DllImport("user32.dll")]
static extern void mouse_event(uint dwFlags, 
    uint dx, 
    uint dy, 
    uint dwData, 
    IntPtr dwExtraInfo);
like image 30
Arseny Avatar answered Oct 28 '22 07:10

Arseny


I was using RealGetWindowClass using the following format.

[DllImport("User32", CallingConvention=CallingConvention.Cdecl)]
public static extern int RealGetWindowClass(IntPtr hwnd, StringBuilder pszType, int cchType);

and i was geting the 'PInvokeStackImbalance' exception/error. But when i changed the CallingConvention to

[DllImport("User32", CallingConvention=CallingConvention.StdCall)]

the error went away. I am using VS2010 on a 64 bit machine.

like image 32
James Poulose Avatar answered Oct 28 '22 07:10

James Poulose