using UnityEngine; using System.Runtime.InteropServices; public enum KeyType { None, // 数字 Digit0, Digit1, Digit2, Digit3, Digit4, Digit5, Digit6, Digit7, Digit8, Digit9, // 字母 A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, // 功能键 F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, // 特殊键 Enter, Backspace, Space, Plus, Minus, // 方向键 ArrowUp, ArrowDown, ArrowLeft, ArrowRight, NumpadDot, 上移,下移,上翻,下翻, } public static class KeyboardSimulator { [DllImport("user32.dll")] private static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize); private const int INPUT_KEYBOARD = 1; private const uint KEYEVENTF_KEYUP = 0x0002; [StructLayout(LayoutKind.Sequential)] private struct INPUT { public int type; public INPUTUNION u; } [StructLayout(LayoutKind.Explicit)] private struct INPUTUNION { [FieldOffset(0)] public KEYBDINPUT ki; } [StructLayout(LayoutKind.Sequential)] private struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public System.UIntPtr dwExtraInfo; } public static ushort GetVK(KeyType type) { switch (type) { // 数字 case KeyType.Digit0: return 0x30; case KeyType.Digit1: return 0x31; case KeyType.Digit2: return 0x32; case KeyType.Digit3: return 0x33; case KeyType.Digit4: return 0x34; case KeyType.Digit5: return 0x35; case KeyType.Digit6: return 0x36; case KeyType.Digit7: return 0x37; case KeyType.Digit8: return 0x38; case KeyType.Digit9: return 0x39; // F1-F10 case KeyType.F1: return 0x70; case KeyType.F2: return 0x71; case KeyType.F3: return 0x72; case KeyType.F4: return 0x73; case KeyType.F5: return 0x74; case KeyType.F6: return 0x75; case KeyType.F7: return 0x76; case KeyType.F8: return 0x77; case KeyType.F9: return 0x78; case KeyType.F10: return 0x79; // 特殊键 case KeyType.Enter: return 0x0D; case KeyType.Backspace: return 0x08; case KeyType.Space: return 0x20; case KeyType.Minus: return 0xBD; case KeyType.Plus: return 0xBB; // 方向键 case KeyType.ArrowUp: return 0x26; case KeyType.ArrowDown: return 0x28; case KeyType.ArrowLeft: return 0x25; case KeyType.ArrowRight: return 0x27; // 字母 default: if (type >= KeyType.A && type <= KeyType.Z) return (ushort)((int)type - (int)KeyType.A + 0x41); break; } return 0; } public static void PressKey(KeyType type) { ushort vk = GetVK(type); if (vk == 0) return; // 特殊处理加号(Shift + =) if (type == KeyType.Plus) { SendKeyDown(0x10); // Shift SendKeyPress(0xBB); // = SendKeyUp(0x10); return; } SendKeyPress(vk); } private static void SendKeyPress(ushort vk) { SendKeyDown(vk); SendKeyUp(vk); } private static void SendKeyDown(ushort vk) { INPUT[] inputs = new INPUT[1]; inputs[0].type = INPUT_KEYBOARD; inputs[0].u.ki.wVk = vk; inputs[0].u.ki.dwFlags = 0; SendInput(1, inputs, Marshal.SizeOf(typeof(INPUT))); } private static void SendKeyUp(ushort vk) { INPUT[] inputs = new INPUT[1]; inputs[0].type = INPUT_KEYBOARD; inputs[0].u.ki.wVk = vk; inputs[0].u.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, inputs, Marshal.SizeOf(typeof(INPUT))); } }