下面是我用来通过 SendInput API 模拟按键的一些代码的摘录。如果我将应用程序设置为针对 x86 CPU 进行编译,这可以正常工作,但不适用于 x64 CPU 编译。
我猜这与 x64 使用双倍大小指针这一事实有关,但我试图将其更改为此[FieldOffset(4)]
但[FieldOffset(8)]
没有奏效。
这可能与它正在导入 32 位版本的 user32.dll 的事实有关吗?
#region SendInput API
[DllImport("user32.dll", EntryPoint = "SendInput", SetLastError = true)]
static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
[DllImport("user32.dll", EntryPoint = "GetMessageExtraInfo", SetLastError = true)]
static extern IntPtr GetMessageExtraInfo();
private enum KeyEvent
{
KeyUp = 0x0002,
KeyDown = 0x0000,
ExtendedKey = 0x0001
}
private struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public long time;
public uint dwExtraInfo;
};
[StructLayout(LayoutKind.Explicit, Size = 28)]
private struct INPUT
{
[FieldOffset(0)]
public uint type;
[FieldOffset(4)]
public KEYBDINPUT ki;
};
#endregion
public void sendKey(KeyCode Key)
{
INPUT[] InputList = new INPUT[2];
INPUT keyInput = new INPUT();
keyInput.type = 1;
keyInput.ki.wScan = 0;
keyInput.ki.time = 0;
keyInput.ki.dwFlags = (int)KeyEvent.KeyDown;
keyInput.ki.dwExtraInfo = (uint)GetMessageExtraInfo();
keyInput.ki.wVk = (ushort)Key;
InputList[0] = keyInput;
keyInput.ki.dwFlags = (int)KeyEvent.KeyUp;
InputList[1] = keyInput;
SendInput((uint)2, InputList, Marshal.SizeOf(InputList[0]));
}