How to use InputSimulator in C#
By FoxLearn 2/15/2025 3:45:58 AM 35
While it’s possible to achieve this using user32.dll
and keybd_event, maintaining this approach can be cumbersome. Fortunately, there’s an easier, more efficient solution with the InputSimulator
library.
This article will walk you through the process of simulating key presses using InputSimulator in C# for WinForms applications.
For example, how to simulate keypress events in C# using keybd_event
from user32.dll
:
// Import the user32.dll [DllImport("user32.dll", SetLastError = true)] static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo); // Define key constants public const int KEYEVENTF_EXTENDEDKEY = 0x0001; // Key down flag public const int KEYEVENTF_KEYUP = 0x0002; // Key up flag public const int VK_RCONTROL = 0xA3; // Right Control key code // Simulate keypress keybd_event(VK_RCONTROL, 0, KEYEVENTF_EXTENDEDKEY, 0); keybd_event(VK_RCONTROL, 0, KEYEVENTF_KEYUP, 0);
Although this method works, it can quickly become difficult to manage and expand. Instead, let’s use InputSimulator, a library designed to simplify simulating keyboard and mouse input.
Why Use InputSimulator?
While the SendKeys
method in WinForms can simulate text input, it doesn’t support simulating individual key strokes. The Windows Input Simulator library, however, allows you to simulate a wide range of keyboard actions, including Control, Alt, Shift, Function keys, and more. It also provides a more intuitive and flexible API for simulating key events.
You can use InputSimulator in WinForms, WPF, and Console applications, and it provides an easy-to-use API to simulate key down, key up, key presses, and even complex keyboard shortcuts.
Getting Started with InputSimulator
1. Installing InputSimulator
To begin simulating key presses in your project, you need to install the InputSimulator library via NuGet. Here’s how:
- Open your WinForms project in Visual Studio.
- In the Solution Explorer, right-click on your project and select Manage NuGet Packages.
- Go to the Browse tab, search for
InputSimulator
, and install the package by Michael Noonan.
Once installed, you can use the library in your classes. For more details and examples, visit the official repository on GitHub.
2. Using InputSimulator
To use InputSimulator, start by including the necessary namespaces:
using WindowsInput; using WindowsInput.Native;
Virtual Key Codes
Each key has a corresponding virtual key code that you’ll need to simulate key events. You can find a list of virtual key codes on Microsoft’s documentation or use the VirtualKeyCode
enum in the WindowsInput.Native
namespace to easily reference each key.
Simulating Key Presses
To simulate a single key press, use the Keyboard.KeyPress
method:
InputSimulator sim = new InputSimulator(); // Simulate pressing various keys sim.Keyboard.KeyPress(VirtualKeyCode.VK_0); // Press "0" sim.Keyboard.KeyPress(VirtualKeyCode.VK_1); // Press "1" sim.Keyboard.KeyPress(VirtualKeyCode.VK_B); // Press "B" sim.Keyboard.KeyPress(VirtualKeyCode.VK_V); // Press "V" sim.Keyboard.KeyPress(VirtualKeyCode.RETURN); // Press Enter sim.Keyboard.KeyPress(VirtualKeyCode.LCONTROL); // Press Left Control
You can also simulate KeyDown
and KeyUp
events with similar methods.
Simulating Keystrokes
To simulate keystrokes or keyboard shortcuts, you can use the ModifiedKeyStroke
method:
InputSimulator sim = new InputSimulator(); // CTRL + C (Copy) sim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_C); // CTRL + K + C (Format Code, for example) sim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, new[] { VirtualKeyCode.VK_K, VirtualKeyCode.VK_C }); // CTRL + ALT + SHIFT + ESC + K sim.Keyboard.ModifiedKeyStroke( new[] { VirtualKeyCode.CONTROL, VirtualKeyCode.MENU, VirtualKeyCode.SHIFT }, new[] { VirtualKeyCode.ESCAPE, VirtualKeyCode.VK_K } );
Typing Text
The TextEntry
method can simulate typing entire words or phrases. The following example simulates typing "Hello World!":
InputSimulator sim = new InputSimulator(); sim.Keyboard.TextEntry("Hello World!");
You can chain API calls to add delays between typing actions:
InputSimulator sim = new InputSimulator(); sim.Keyboard.Sleep(1000) // Wait 1 second before typing .TextEntry("Hello World!") .Sleep(1000) // Wait 1 second after typing .TextEntry("More text");
Simulating Typing by Characters
For a more advanced use case, you can simulate typing text one character at a time, with delays between each character:
private void simulateTypingText(string text, int typingDelay = 100, int startDelay = 0) { InputSimulator sim = new InputSimulator(); sim.Keyboard.Sleep(startDelay); // Start delay string[] lines = text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); int totalLines = lines.Length; int currentLine = 1; foreach (string line in lines) { char[] characters = line.ToCharArray(); foreach (char character in characters) { sim.Keyboard.TextEntry(character).Sleep(typingDelay); } Console.WriteLine($"Percent: {(float)currentLine / totalLines * 100}%"); // Add a new line sim.Keyboard.KeyPress(VirtualKeyCode.RETURN); currentLine++; } }
This method simulates typing text with a customizable typing delay for a more human-like effect. You can also introduce a delay before starting or between lines.
- Registering Global Hotkeys in WinForms
- How to implement Sciter in C#
- Hiding Data in Images Using Steganography in C#
- How to access a SFTP server using SSH.NET in C#
- Current Thread Must Be Set to Single Thread Apartment (STA) Mode
- How to Run a C# WinForms App with Administrator Rights
- How to Identify the Antivirus Software Installed on a PC Using C#
- How to Append a file in C#