Learn how to simulate keypress event from any key in the keyboard using the awesome InputSimulator library in Windows Forms.

Simulating keypress in the right way using InputSimulator with C# in Winforms

Surely all the C# developers that work with Winforms, knows snippets that allows to simulate a keypress of any key as long as you know the code:

// Import the user32.dll
[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo); 

// Declare some keyboard keys as constants with its respective code
// See Virtual Code Keys: https://msdn.microsoft.com/en-us/library/dd375731(v=vs.85).aspx
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 a key press event
keybd_event(VK_RCONTROL, 0, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(VK_RCONTROL, 0, KEYEVENTF_KEYUP, 0); 

However this can become a headache to maintain. That's why in this article, we are going to show you the right way to simulate keypress events using InputSimulator. The Windows Input Simulator provides a simple .NET (C#) interface to simulate Keyboard or Mouse input using the Win32 SendInput method. All of the Interop is done for you and there's a simple programming model for sending multiple keystrokes.

Advantages of working with InputSimulator

Windows Forms provides the SendKeys method which can simulate text entry, but not actual key strokes. Windows Input Simulator can be used in WPF, Windows Forms and Console Applications to synthesize or simulate any Keyboard input including Control, Alt, Shift, Tab, Enter, Space, Backspace, the Windows Key, Caps Lock, Num Lock, Scroll Lock, Volume Up/Down and Mute, Web, Mail, Search, Favorites, Function Keys, Back and Forward navigation keys, Programmable keys and any other key defined in the Virtual Key table. It provides a simple API to simulate text entry, key down, key up, key press and complex modified key strokes and chords.

Want to get started with this library? Then keep reading !

1. Install InputSimulator

The first you need to simulate keypress and keystrokes easily is to install the library in your project via nuGet. Open your Winforms C# project and open the NuGet package manager in the solution explorer:

Go to the Browse tab and search for InputSimulator:

InputSimulator nuget install

From the list select the package by Michael Noonan and install it. Once the installation of the package finishes, you will be able to use it in your classes. For more information about this library and examples please visit the official repository at Github here.

2. Using InputSimulator

Before using Input Simulator you will need to include the required types at the top of your classes:

using WindowsInput.Native; 
using WindowsInput;

Virtual code list

If you want to simulate the keypress event of any key, you will need it's keycode that you can get on this list. However you can just simply use the enum property of WindowsInput.Native.VirtualKeyCode that has a property for every key.

Simulate Keypress

To simulate a single keypress event, use the Keyboard.KeyPress method that expects the virtual key code of the key you want to simulate:

InputSimulator sim = new InputSimulator();

// Press 0 key
sim.Keyboard.KeyPress(VirtualKeyCode.VK_0);
// Press 1
sim.Keyboard.KeyPress(VirtualKeyCode.VK_1);
// Press b
sim.Keyboard.KeyPress(VirtualKeyCode.VK_B);
// Press v
sim.Keyboard.KeyPress(VirtualKeyCode.VK_V);
// Press enter
sim.Keyboard.KeyPress(VirtualKeyCode.RETURN);
// Press Left CTRL button
sim.Keyboard.KeyPress(VirtualKeyCode.LCONTROL);

As mentioned, this logic isn't limited to a single keypress event but too for KeyDown and KeyUp too.

Simulate Keystrokes

If you want to simulate keystrokes or keyboard shortcuts, you can use the ModifiedKeyStroke function of the Keyboard:

InputSimulator sim = new InputSimulator();

// CTRL + C (effectively a copy command in many situations)
sim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_C);

// You can simulate chords with multiple modifiers
// For example CTRL + K + C whic is simulated as
// CTRL-down, K, C, CTRL-up
sim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, new[] {
    VirtualKeyCode.VK_K, VirtualKeyCode.VK_C
});

// You can simulate complex chords with multiple modifiers and key presses
// For example CTRL-ALT-SHIFT-ESC-K which is simulated as
// CTRL + down, ALT + down, SHIFT + down, press ESC, press K, SHIFT-up, ALT-up, CTRL-up
sim.Keyboard.ModifiedKeyStroke(
    new[] { VirtualKeyCode.CONTROL, VirtualKeyCode.MENU, VirtualKeyCode.SHIFT },
    new[] { VirtualKeyCode.ESCAPE, VirtualKeyCode.VK_K }
);

Type entire words

The TextEntry method of the Keyboard simulates uninterrupted text entry via the Keyboard:

InputSimulator Simulator = new InputSimulator();

Simulator.Keyboard.TextEntry("Hello World !");

The simulator API is chainable, so you can use the Sleep method to wait some milliseconds before starting or after typing something:

InputSimulator Simulator = new InputSimulator();
            
// Wait a second to start typing
Simulator.Keyboard.Sleep(1000)
// Type Hello World    
.TextEntry("Hello World !")
// Wait another second
.Sleep(1000)
// Type More text
.TextEntry("Type another thing")
;

Simulate typing of text by characters

If you are lazy and want to create snippets that make your life easier, you may want to create some type of roboscript that writes some text for you. Obviously the text needs to exist already so it can be used in projects like videos where you can't type errors:

/// <summary>
/// Simulate typing of any text as you do when you write.
/// </summary>
/// <param name="Text">Text that will be written automatically by simulation.</param>
/// <param name="typingDelay">Time in ms to wait after 1 character is written.</param>
/// <param name="startDelay"></param>
private void simulateTypingText(string Text, int typingDelay = 100, int startDelay = 0)
{
    InputSimulator sim = new InputSimulator();

    // Wait the start delay time
    sim.Keyboard.Sleep(startDelay);

    // Split the text in lines in case it has
    string[] lines = Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);

    // Some flags to calculate the percentage
    int maximum = lines.Length;
    int current = 1;

    foreach (string line in lines)
    {
        // Split line into characters
        char[] words = line.ToCharArray();
        
        // Simulate typing of the char i.e: a, e , i ,o ,u etc
        // Apply immediately the typing delay
        foreach (char word in words)
        {
            sim.Keyboard.TextEntry(word).Sleep(typingDelay);
        }

        float percentage = ((float)current / (float)maximum) * 100;

        current++;

        // Add a new line by pressing ENTER
        // Return to start of the line in your editor with HOME
        sim.Keyboard.KeyPress(VirtualKeyCode.RETURN);
        sim.Keyboard.KeyPress(VirtualKeyCode.HOME);

        // Show the percentage in the console
        Console.WriteLine("Percent : {0}", percentage.ToString());
    }
}

The method expects as first argument the text that will be typed as an human would do. The default typing delay is of 100 milliseconds which is usually the typing delay of an human after every keypress. The last argument is optional and provides only a time delay when to start typing:

// Simulate typing text of a textbox multiline
simulateTypingText(textBox1.Text);

// Simulate typing slowly by waiting half second after typing every character
simulateTypingText(textBox1.Text, 500);

// Simulate typing slowly by waiting half second after typing every character
// and wait 5 seconds before starting
simulateTypingText(textBox1.Text, 500, 5000);

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors