2010-07-08 27 views
4

我已经手动使用此代码来模拟系统通过代码点击鼠标。我应该怎么做使这个代码在VS 2010中工作?

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 
} 

但现在我使用VS 2010和Windows 7和我得到的错误在此代码的执行,现在

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

因此,对于这个有什么建议?

错误我遇到的是:

PInvokeStackImbalance检测

对PInvoke函数'ClickingApp!ClickingApp.Form1 :: mouse_event'的调用使堆栈不平衡。这很可能是因为托管的PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否与目标非托管签名相匹配。

回答

5

问题是与P/Invoke签名试试这个。

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

DWORD是32位,而C#长为64位

而且只注意到您指定的调用约定,最好是,使用P时,不指定它/调用的Windows API,或您可以使用CallingConvention.Winapi,错误的调用约定通常是堆栈不平衡的原因。

+0

请问你解释调用约定的事情,因为我不知道它... $ – Mobin 2010-07-08 18:12:07

+1

@Mobin,调用约定定义参数如何传递给函数,以及谁负责在函数完成时清理堆栈。例如C中的一个典型调用约定,参数以相反的顺序压入堆栈,调用者负责堆栈清理,而stdcall调用约定是它自己负责清理堆栈的函数。函数使用特定的调用约定进行编译,如果调用者使用错误的约定,堆栈将处于不一致的状态。 – 2010-07-08 18:18:32

+0

哦谢谢先生!我知道了 :) – Mobin 2010-07-09 19:37:04