编程语言
首页 > 编程语言> > C#-P / Invoke-Int 4字节,尝试更改为UInt,但会导致问题

C#-P / Invoke-Int 4字节,尝试更改为UInt,但会导致问题

作者:互联网

错误似乎很常见,但在这里是:

eCA1901 P/Invoke declarations should be portable    As it is declared in your code, parameter 'dwExtraInfo' of P/Invoke 'NativeMethods.mouse_event(int, int, int, int, int)' will be 4 bytes wide on 64-bit platforms. This is not correct, as the actual native declaration of this API indicates it should be 8 bytes wide on 64-bit platforms. Consult the MSDN Platform SDK documentation for help determining what data type should be used instead of 'int'

这是代码行:

[System.Runtime.InteropServices.DllImport("user32.dll")]
internal static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

现在,我已尝试将Uin更改为与64bit兼容的Uint或soemthing,或者可以在两者上使用(Pint或其他名称,无法记住名称).

但是,如果我从Int更改为Uint或其他内容,它将破坏此代码:

if (click == "Left")
{
    NativeMethods.mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, MousePosition.X, MousePosition.Y, MousePosition.X, MousePosition.Y);
}
if (click == "Right")
{
    NativeMethods.mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, MousePosition.X, MousePosition.Y, MousePosition.X, MousePosition.Y);
}
if (down == "Left"+"True")
{
    NativeMethods.mouse_event(MOUSEEVENTF_LEFTDOWN , MousePosition.X, MousePosition.Y, MousePosition.X, MousePosition.Y);
}
if (down == "Right"+"True")
{
    NativeMethods.mouse_event(MOUSEEVENTF_RIGHTDOWN, MousePosition.X, MousePosition.Y, MousePosition.X, MousePosition.Y);
}

如其所说(无法从int转换…)
如果我在此处的所有内容都使用(uint),则似乎“有效”,但我认为这不是一种最佳方法.

这是MouseEvent代码:

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

还尝试将其更改为Uint.

现在,我为什么继续谈论Uint是因为我读到我应该将其更改为该名称.
我没有真正的线索将Uint与Int进行比较.

因此,如果有更好的方法,或者我做错了,请告诉.

解决方法:

原始声明:

VOID WINAPI mouse_event(
  _In_  DWORD dwFlags,
  _In_  DWORD dx,
  _In_  DWORD dy,
  _In_  DWORD dwData,
  _In_  ULONG_PTR dwExtraInfo
);

正确的C#声明(可能的选项之一):

[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern void mouse_event(
    int dwFlags, int dx, int dy, int dwData, IntPtr dwExtraInfo);

为什么最后一个参数声明为IntPtr:

因为它是原始声明中的指针类型,所以在64位处理的情况下它将是8个字节. IntPtr对于32位进程是4个字节,对于64位进程是8个字节,这意味着如果您要将程序集编译为AnyCPU或x64,则mouse_event代码保持不变.

如果您不想每次使用mouse_event都将最后一个参数强制转换为(IntPtr),则可以提供一个重载来实现:

static void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo)
{
    mouse_event(dwFlags, dx, dy, dwData, (IntPtr)dwExtraInfo);
}

另外,我认为您没有提供dwData&的有效值. dwExtraInfo参数.请确保您遵循文档:MSDN

标签:c,64-bit,pinvoke
来源: https://codeday.me/bug/20191122/2063785.html