对PInvoke函数的调用...使堆栈失衡

时间:2016-05-22 12:47:58

标签: c# pinvoke

每次我调用函数mouse_event我都会收到错误

  

对PInvoke函数的调用使堆栈失衡。这很可能是因为托管PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配。

const int MOUSEEVENTF_LEFTDOWN = 0x02;
    const int MOUSEEVENTF_LEFTUP = 0x04;
    const int MOUSEEVENTF_RIGHTDOWN = 0x08;
    const int MOUSEEVENTF_RIGHTUP = 0x10;

    [System.Runtime.InteropServices.DllImport("user32.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl)]
    public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);


switch (mouseAction)
        {
            case ENUMMouseAction.LEFTDOWN:
                mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
                break;
            case ENUMMouseAction.LEFTUP:
                mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
                break;
            case ENUMMouseAction.RIGHTDOWN:
                mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
                break;
            case ENUMMouseAction.RIGHTUP:
                mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
                break;
        }

我已经尝试了所有可用的CallingConventions,似乎没有任何工作,任何帮助将不胜感激,

提前谢谢。

1 个答案:

答案 0 :(得分:1)

两个错误:

  • 调用约定应为Stdcall
  • 参数类型都错了。前四个参数是uint,最后一个参数是UIntPtr

阅读文档时需要注意。可在此处找到:https://msdn.microsoft.com/en-us/library/windows/desktop/ms646260.aspx