views:

88

answers:

1

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.

+5  A: 

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.

Chris Taylor
Will you please explain the calling convention thing because i am unaware of it ...:$
Mobin
@Mobin, the calling convention defines how arguments are passed to the function and who is responsible for cleaning the stack up when the function completes. For example a typical calling convention in C, the parameters are pushed on the stack in reverse order and the caller is responsible for the stack clean up, while the stdcall calling convention the function it self is responsible for the clean up of the stack etc. A function is compiled with a specific calling convention and if the caller use the wrong convention the stack is left in an inconsistent state.
Chris Taylor
Oh thanks sir !!! I got it :)
Mobin