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

本文关键字:UInt 问题 Invoke-Int 4字节 | 更新日期: 2023-09-27 18:26:25

错误似乎很常见,但它是:

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);

现在我已经尝试切换到与64位兼容的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),这似乎是"有效的",但我不认为这是一种非常理想的方法。

这是鼠标事件代码:

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.相比是什么

所以,如果有更好的方法,或者我做错了,请告诉我。

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

原始声明:

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字节,这意味着如果要将程序集编译为AnyCPUx64,则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&CCD_ 8参数。请确保遵循以下文档:MSDN