| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading.Tasks;
- internal class SimulateInput
- {
- // 定义 INPUT 结构 (用于 SendInput)
- [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 KEYBDINPUT
- {
- public ushort wVk;
- public ushort wScan;
- public uint dwFlags;
- public uint time;
- public IntPtr dwExtraInfo;
- }
- [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 HARDWAREINPUT
- {
- public uint uMsg;
- public ushort wParamL;
- public ushort wParamH;
- }
- // 常量
- private const uint INPUT_KEYBOARD = 1;
- private const uint KEYEVENTF_KEYUP = 0x0002;
- public const ushort VK_LWIN = 0x5B; // 左 Windows 键
- public const ushort VK_RWIN = 0x5C; // 右 Windows 键
- public const ushort VK_BACKSPACE = 0x08; // 后退
- public const ushort VK_UP = 0x26; // 上
- public const ushort VK_DOWN = 0x28; // 下
- public const ushort VK_NUM0 = 0x30;
- public const ushort VK_NUM1 = 0x31;
- public const ushort VK_NUM2 = 0x32;
- public const ushort VK_NUM3 = 0x33;
- public const ushort VK_NUM4 = 0x34;
- public const ushort VK_NUM5 = 0x35;
- public const ushort VK_NUM6 = 0x36;
- public const ushort VK_NUM7 = 0x37;
- public const ushort VK_NUM8 = 0x38;
- public const ushort VK_NUM9 = 0x39;
- public const ushort VK_DOT = 0xBE;
- // 导入 SendInput 函数
- [DllImport("user32.dll", SetLastError = true)]
- static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);
- public static void SimulateKey(ushort keyCode)
- {
- INPUT input = new INPUT();
- input.type = INPUT_KEYBOARD;
- input.u.ki.wVk = keyCode; // 使用左 Windows 键
- input.u.ki.wScan = 0; // 虚拟键码模式,wScan 可为 0
- input.u.ki.dwFlags = 0; // 按下 (keydown)
- input.u.ki.time = 0;
- input.u.ki.dwExtraInfo = IntPtr.Zero;
- // 发送 "按下" 事件
- SendInput(1, ref input, Marshal.SizeOf(typeof(INPUT)));
- // 可选:短暂延迟 (模拟按键时长)
- // System.Threading.Thread.Sleep(50);
- // 发送 "释放" 事件
- input.u.ki.dwFlags = KEYEVENTF_KEYUP; // 释放 (keyup)
- SendInput(1, ref input, Marshal.SizeOf(typeof(INPUT)));
- }
- }
|