Mobin
Mobin

Reputation: 4920

What should i do make this code work in VS 2010?

I have used this code manually to simulate a mouse click by system through 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's 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 get the error on execution of this code now

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

So any suggestions for this ...

The error i encounter is:

PInvokeStackImbalance was Detected

A call to PInvoke function 'ClickingApp!ClickingApp.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.

Upvotes: 4

Views: 1365

Answers (1)

Chris Taylor
Chris Taylor

Reputation: 53699

The problem is with the P/Invoke signature try this.

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

DWORD is 32 bits while a C# long is 64 bits

Also just noticed you are specifying the calling convention, it is better to not specify it when using P/Invoke for the Windows API, or you could using CallingConvention.Winapi, the wrong calling convention is typically the cause of a stack imbalance.

Upvotes: 5

Related Questions