Search code examples
c#sendkeyskeystroke

How to simulate Keystrokes in C#?


Google gives this but it seems to only work for a WindowsForms class. I'm completely new to C#. What I'm trying to make is a program that monitors for an event, and then (for example), acts as if the 'H' key has been pressed. I don't really want to worry about what the active window is or anything, or sending a keystroke to an application, I just want the program to act as if I have physically pressed the 'H' button on my keyboard. The SendKeys class doesn't seem to work in a general class. Am I going about this completely the wrong way?


Solution

  • From How to: Simulate Mouse and Keyboard Events in Code:

    Windows Forms provides several options for programmatically simulating mouse and keyboard input.

    Simulating Mouse Input
    The best way to simulate mouse events is to call the OnEventName method that raises the mouse event you want to simulate.

    Simulating Keyboard Input
    Although you can simulate keyboard input by using the strategies discussed above for mouse input, Windows Forms also provides the SendKeys class for sending keystrokes to the active application.