在C#中,SendInput方法用于模擬用戶輸入,如鍵盤按鍵和鼠標(biāo)事件。它可以用來自動(dòng)化測(cè)試、模擬用戶操作等場(chǎng)景。
下面是一個(gè)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]));
}
}
使用以上代碼,你可以調(diào)用InputSimulator類的SendKey方法來模擬按下指定的鍵盤按鍵。例如,若要模擬按下A鍵,可以這樣調(diào)用:
InputSimulator.SendKey(0x41);
上述示例僅演示了如何模擬鍵盤事件,你也可以根據(jù)需要,擴(kuò)展代碼以支持鼠標(biāo)事件等其他功能。