c#中sendinput的用法是什么
导读:在C#中,SendInput方法用于模拟用户输入,如键盘按键和鼠标事件。它可以用来自动化测试、模拟用户操作等场景。 下面是一个SendInput方法的示例代码: using System; using System.Runtime.Inte...
在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);
上述示例仅演示了如何模拟键盘事件,你也可以根据需要,扩展代码以支持鼠标事件等其他功能。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c#中sendinput的用法是什么
本文地址: https://pptw.com/jishu/680060.html