在C#中,SendInput方法用于模擬用戶輸入,如鍵盤按鍵和鼠標事件。它可以用來自動化測試、模擬用戶操作等場景。
下面是一個SendInput方法的示例代碼:
using System;
using System.Runtime.InteropServices;
public class InputSimulator
{
[DllImport("user32.dll", SetLastError = true)]
private static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
[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;
}
public struct MOUSEINPUT
{
public int dx;
public int dy;
public uint mouseData;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
public struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
public static void SendKey(ushort key)
{
INPUT[] inputs = new INPUT[1];
inputs[0].type = 1; // Input is a keyboard event
inputs[0].u.ki.wVk = key;
inputs[0].u.ki.dwFlags = 0; // Key press
SendInput(1, inputs, Marshal.SizeOf(inputs[0]));
}
}
使用以上代碼,你可以調用InputSimulator類的SendKey方法來模擬按下指定的鍵盤按鍵。例如,若要模擬按下A鍵,可以這樣調用:
InputSimulator.SendKey(0x41);
上述示例僅演示了如何模擬鍵盤事件,你也可以根據需要,擴展代碼以支持鼠標事件等其他功能。