c# - 我应该怎么做才能使这段代码在 VS 2010 中工作?

标签 c# visual-studio-2010 mouse mouseevent

我已经手动使用此代码通过代码模拟系统的鼠标点击。

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 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.

最佳答案

问题出在 P/Invoke 签名上试试这个。

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

DWORD 是 32 位,而 C# long 是 64 位

还注意到您正在指定调用约定,最好在为 Windows API 使用 P/Invoke 时不指定它,或者您可以使用 CallingConvention.Winapi,错误的调用约定通常是堆栈不平衡的原因.

关于c# - 我应该怎么做才能使这段代码在 VS 2010 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3206529/

相关文章:

c# - 将 pinvoke 与结构和指针一起使用

c# - 对于条件 VB.NET 与 C#

c# - 如何使用 Python 和 .NET/C# 自动化 Princeton Instruments LightField

c# - 在剪贴板中查找图像类型

c# - 在 Visual Studio 2010 语言服务中实现查找引用

c++ winsock 代码在 visual studio 2010 中的原始解决方案/项目中不起作用

c++ - 错误 C2059 : syntax error : 'generic'

java - 按下按钮的计数

c# - 在 C# 中捕获和发送键盘/鼠标输入

javascript - 获取 jquery.media 对象上的鼠标位置