我正在尝试使用 C# 中的
SendInput()
来模拟鼠标和键盘事件。鼠标模拟完美,键盘模拟不行。
在这种情况下,我尝试使用另一种语言来挂钩键盘以确定它是否真的有效,但我无法挂钩任何东西。我尝试查看是否有错误,但是
Marshal.GetLastWin32Error()
返回0
,这意味着没有错误。我也尝试以管理员身份运行,但没有成功。
之后,我在StackOverflow上发现了类似的情况,我尝试将代码改为
KeyEventFlags.KEYDOWN | KeyEventFlags.SCANCODE
和KeyEventFlags.KEYDOWN | KeyEventFlags.UNICODE
,但都不起作用。
这是代码:
[DllImport("user32.dll", SetLastError = true)]
public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
KEYBDINPUT keyboardInput = new KEYBDINPUT();
keyboardInput.dwFlags = (uint)(KeyEventFlags.KEYDOWN);
keyboardInput.wVk = (ushort)'A';
InputUnion union = new InputUnion();
union.ki = keyboardInput;
INPUT[] input = new INPUT[1];
input[0].type = (uint)InputTypes.KEYBOARD;
input[0].U = union;
Console.WriteLine(SendInput(1, input, Marshal.SizeOf(union)));
Console.WriteLine(Marshal.GetLastWin32Error());
这是定义枚举的代码:
public enum InputTypes : uint
{
MOUSE = 0,
KEYBOARD = 1,
HARDWARE = 2
}
public enum MouseEventFlags : uint
{
ABSOLUTE = 0x8000,
LEFTDOWN = 0x0002,
LEFTUP = 0x0004,
MIDDLEDOWN = 0x0020,
MIDDLEUP = 0x0040,
MOVE = 0x0001,
RIGHTDOWN = 0x0008,
RIGHTUP = 0x0010,
WHEEL = 0x0800,
XDOWN = 0x0080,
XUP = 0x0100,
HWHEEL = 0x01000
}
public enum KeyEventFlags : ushort
{
KEYDOWN = 0x0000,
EXTENDEDKEY = 0x0001,
KEYUP = 0x0002,
UNICODE = 0x0004,
SCANCODE = 0x0008
}
[StructLayout(LayoutKind.Sequential)]
public struct INPUT
{
public uint type;
public InputUnion U;
}
[StructLayout(LayoutKind.Explicit)]
public struct InputUnion
{
[FieldOffset(0)]
public MOUSEINPUT mi;
[FieldOffset(0)]
public KEYBDINPUT ki;
[FieldOffset(0)]
public HARDWAREINPUT hi;
}
[StructLayout(LayoutKind.Sequential)]
public struct MOUSEINPUT
{
public int dx;
public int dy;
public uint mouseData;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct HARDWAREINPUT
{
public uint uMsg;
public ushort wParamL;
public ushort wParamH;
}
我想知道为什么这不起作用,以及我错在哪一步。
我过去曾为此使用过 SendKeys。 占用com端口的条码扫描仪可以将扫描数据发送到具有焦点的窗口。
foreach (char c in line + "\r\n")
{
System.Windows.Forms.SendKeys.SendWait("" + c);
}
更多信息在这里