介绍:
该程序本意是为了在彩六里打中文用的,现整理出来供大家复制粘贴。(源程序已开源至GitHub - 彩六中文输入)
主要使用SendInput函数,与c语言中用法一致。(部分代码来自网络)
命名空间部分
using static System.Threading.Thread; using System.Runtime.InteropServices;
结构体和函数声明部分
[StructLayout(LayoutKind.Explicit)] public struct INPUT { [FieldOffset(0)] public int type; [FieldOffset(4)] public KEYBDINPUT ki; [FieldOffset(4)] public MOUSEINPUT mi; [FieldOffset(4)] public HARDWAREINPUT hi; } public struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public int dwFlags; public int time; public IntPtr dwExtraInfo; } public struct KEYBDINPUT { public short wVk; public short wScan; public int dwFlags; public int time; public IntPtr dwExtraInfo; } public struct HARDWAREINPUT { public int uMsg; public short wParamL; public short wParamH; } [DllImport("user32")] public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
自定义函数封装部分
public void SimulateInputString(char c) { INPUT[] input = new INPUT[2]; input[0].type = 1; input[0].ki.wVk = 0;//dwFlags 为KEYEVENTF_UNICODE 即4时,wVk必须为0 input[0].ki.wScan = (short)c; input[0].ki.dwFlags = 4;//输入UNICODE字符 input[0].ki.time = 0; input[0].ki.dwExtraInfo = IntPtr.Zero; input[1].type = 1; input[1].ki.wVk = 0; input[1].ki.wScan = (short)c; input[1].ki.dwFlags = 6; input[1].ki.time = 0; input[1].ki.dwExtraInfo = IntPtr.Zero; SendInput(2u, input, Marshal.SizeOf((object)default(INPUT))); } public void SimulateInputKey(int key) { INPUT[] input = new INPUT[1]; input[0].type = 1;//模拟键盘 input[0].ki.wVk = (short)key; input[0].ki.dwFlags = 0;//按下 SendInput(1u, input, Marshal.SizeOf((object)default(INPUT))); Sleep(50); input[0].type = 1;//模拟键盘 input[0].ki.wVk = (short)key; input[0].ki.dwFlags = 2;//抬起 SendInput(1u, input, Marshal.SizeOf((object)default(INPUT))); Sleep(50); }
说明:
SimulateInputString为发送单个字符文本;
SimulateInputKey为模拟按键按下和抬起,参数key为虚拟键码;
关于键码的列表,可以查看微软文档:https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes