/// <summary> /// Effectively sends the keyboard input command. /// </summary> /// <param name="keyCode">The key code to send. Can be the scan code or the virtual key code.</param> /// <param name="isKeyDown">Flag if the key should be pressed or released.</param> /// <param name="isScanCode">Flag if the code is the scan code or the virtual key code.</param> /// <param name="isExtended">Flag if the key is an extended key.</param> /// <param name="isUnicode">Flag if the key is unicode.</param> private static void SendInput(ushort keyCode, bool isKeyDown, bool isScanCode, bool isExtended, bool isUnicode) { // Prepare the basic object var keyboardInput = new KEYBDINPUT { time = 0, dwExtraInfo = User32.GetMessageExtraInfo(), }; // Add the "key-up" flag if needed. By default it is "key-down" if (!isKeyDown) { keyboardInput.dwFlags |= KeyEventFlags.KEYEVENTF_KEYUP; } if (isScanCode) { keyboardInput.wScan = keyCode; keyboardInput.dwFlags |= KeyEventFlags.KEYEVENTF_SCANCODE; // Add the extended flag if the flag is set or the keycode is prefixed with the byte 0xE0 // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms646267(v=vs.85).aspx if (isExtended || (keyCode & 0xFF00) == 0xE0) { keyboardInput.dwFlags |= KeyEventFlags.KEYEVENTF_EXTENDEDKEY; } } else if (isUnicode) { keyboardInput.dwFlags |= KeyEventFlags.KEYEVENTF_UNICODE; keyboardInput.wScan = keyCode; } else { keyboardInput.wVk = keyCode; } // Build the input object var input = INPUT.KeyboardInput(keyboardInput); // Send the command if (User32.SendInput(1, new[] { input }, INPUT.Size) == 0) { // An error occured var errorCode = Marshal.GetLastWin32Error(); Logger.Default.Warn("Could not send keyboard input. ErrorCode: {0}", errorCode); } if (WindowsVersion.IsWindows10()) { Wait.For(TimeSpan.FromMilliseconds(10)); } }
public static void SendInput(KEYBDINPUT keyboardInput) { // Demand the correct permissions var permissions = new PermissionSet(PermissionState.Unrestricted); permissions.Demand(); if (User32.SendInput(1, new[] { INPUT.KeyboardInput(keyboardInput) }, INPUT.Size) == 0) { throw new Win32Exception(); } }
/// <summary> /// Synthesizes keystrokes, mouse motions, and button clicks. /// </summary> /// <param name="keyCode">Key code</param> /// <param name="isKeyDown">Whether the button is pressed</param> public static void SendInput(ushort keyCode, bool isKeyDown) { KEYBDINPUT keyboardInput = new KEYBDINPUT { time = 0, dwExtraInfo = User32.GetMessageExtraInfo() }; if (isKeyDown == false) { keyboardInput.dwFlags |= KeyEventFlags.KEYEVENTF_KEYUP; } keyboardInput.wVk = keyCode; var input = INPUT.KeyboardInput(keyboardInput); User32.SendInput(1, new[] { input }, INPUT.Size); }