How can I programmatically generate keypress events in C#?

160,278

Solution 1

The question is tagged WPF but the answers so far are specific WinForms and Win32.

To do this in WPF, simply construct a KeyEventArgs and call RaiseEvent on the target. For example, to send an Insert key KeyDown event to the currently focused element:

var key = Key.Insert;                    // Key to send
var target = Keyboard.FocusedElement;    // Target element
var routedEvent = Keyboard.KeyDownEvent; // Event to send
     target.RaiseEvent(
  new KeyEventArgs(
    Keyboard.PrimaryDevice,
    PresentationSource.FromVisual(target),
    0,
    key)
  { RoutedEvent=routedEvent }
);

This solution doesn't rely on native calls or Windows internals and should be much more reliable than the others. It also allows you to simulate a keypress on a specific element.

Note that this code is only applicable to PreviewKeyDown, KeyDown, PreviewKeyUp, and KeyUp events. If you want to send TextInput events you'll do this instead:

var text = "Hello";
var target = Keyboard.FocusedElement;
var routedEvent = TextCompositionManager.TextInputEvent;

target.RaiseEvent(
  new TextCompositionEventArgs(
    InputManager.Current.PrimaryKeyboardDevice,
    new TextComposition(InputManager.Current, target, text))
  { RoutedEvent = routedEvent }
);

Also note that:

  • Controls expect to receive Preview events, for example PreviewKeyDown should precede KeyDown

  • Using target.RaiseEvent(...) sends the event directly to the target without meta-processing such as accelerators, text composition and IME. This is normally what you want. On the other hand, if you really do what to simulate actual keyboard keys for some reason, you would use InputManager.ProcessInput() instead.

Solution 2

To produce key events without Windows Forms Context, We can use the following method,

[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);

sample code is given below:

const int VK_UP = 0x26; //up key
const int VK_DOWN = 0x28;  //down key
const int VK_LEFT = 0x25;
const int VK_RIGHT = 0x27;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
int press()
{
    //Press the key
    keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
    return 0;
}

List of Virtual Keys are defined here.

To get the complete picture, please use the below link, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html

Solution 3

I've not used it, but SendKeys may do what you want.

Use SendKeys to send keystrokes and keystroke combinations to the active application. This class cannot be instantiated. To send a keystroke to a class and immediately continue with the flow of your program, use Send. To wait for any processes started by the keystroke, use SendWait.

System.Windows.Forms.SendKeys.Send("A");
System.Windows.Forms.SendKeys.Send("{ENTER}");

Microsoft has some more usage examples here.

Solution 4

Easily! (because someone else already did the work for us...)

After spending a lot of time trying to this with the suggested answers I came across this codeplex project Windows Input Simulator which made it simple as can be to simulate a key press:

  1. Install the package, can be done or from the NuGet package manager or from the package manager console like:

    Install-Package InputSimulator

  2. Use this 2 lines of code:

    inputSimulator = new InputSimulator() inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)

And that's it!

-------EDIT--------

The project page on codeplex is flagged for some reason, this is the link to the NuGet gallery.

Solution 5

Windows SendMessage API with send WM_KEYDOWN.

Share:
160,278

Related videos on Youtube

Dan Vogel
Author by

Dan Vogel

Software Developer for a data backup and protection company. Currently coding in C# and C++. Developing UI using WPF. Beginner Android developer under the covers with a flashlight.

Updated on July 08, 2022

Comments

  • Dan Vogel
    Dan Vogel almost 2 years

    How can I programmatically create an event that would simulate a key being pressed on the keyboard?

    • Daniel A. White
      Daniel A. White over 14 years
      Do you just need the event to fire?
    • Jonas B
      Jonas B over 14 years
      I think you'd have to step into unmanaged code in order to simulate a 'real' keypress.
    • Dan Vogel
      Dan Vogel over 14 years
      Yes, I just need the event to fire.
    • GONeale
      GONeale almost 12 years
      No @EdS. there are perfectly valid reasons for this, such as for developing a keypad.
    • Ed S.
      Ed S. almost 12 years
      @GONeale: Wow, a three year old comment. Ok then. Yes, there are valid uses for this, that;s why the API exists in the first place. They are however few and far between. In my experience many people do this because they don't really understand the best way to tackle a problem, i.e., "I want to call the code in my button click event handler, but not only when a button is clicked". So, for a beginner, it seems logical to simulate a button click, when what they really should do is take that code, throw it into a function, and call it from elsewhere in the code.
    • Ed S.
      Ed S. almost 12 years
      @GONeale: Due to the poor quality of the question I assumed a beginner, and then I assumed that this is probably not the best way to solve the problem at hand. Sure, I may have been wrong, but more often than not I will be right. That said, I could have left a more helpful comment. Hopefully I have gotten better over the course of the last three years :)
    • Dan Vogel
      Dan Vogel almost 12 years
      @EdS: The question was pretty to the point. I could have added a lot of excess detail about creating a keypad, and still got the same answer. Considering I got exactly what I needed, it doesn't seem like a "poor quality" question to me.
    • Karolis Kajenas
      Karolis Kajenas over 8 years
      @EdS. Also it could be used to tests, to simulate user's input.
  • Dan Vogel
    Dan Vogel over 14 years
    I tried using SendKeys.Send and I get this InvalidOperationException: "SendKeys cannot run inside this application because the application is not handling Windows messages. Either change the application to handle messages, or use the SendKeys.SendWait method." Using SendKey.SendWait has no effect.
  • Dan Vogel
    Dan Vogel over 14 years
    I just tried your suggestion, I see no effect. I've attached a keyDown event handler to the focused element. The event I've raised is recieved, but the KeyState is None, the ScanCode is 0, and isDown is false. I assume I am getting these values because this is the actual state of the keyboard. Hitting a key on the actual keyboard, KeyState = Down, isDown=true, and ScanCode has a value.
  • Michael Petrotta
    Michael Petrotta over 14 years
    Make sure you're not sending the key event to yourself. Switch focus to the proper process before sending the event. The second linked article has some help on that.
  • Ray Burns
    Ray Burns over 14 years
    Yes, KeyState=None and IsDown=false because they give the actual state of the keyboard. But KeyState, IsDown and ScanCode are not used anywhere in Microsoft's WPF code so unless you have some custom controls that use them it doesn't matter. Your problem is more likely that the code is looking for PreviewKeyDown instead of KeyDown, or it is using TextInput events, which are sent separately (for example, a TextBox uses TextInput events), or you want to invoke accelerators for which you need InputManager.ProcessEvent. But normally you don't want to do this.
  • Ray Burns
    Ray Burns over 14 years
    I edited my answer and added details on how to use TextInput events.
  • kartal
    kartal almost 14 years
    when I tried the first code of keydown I got error in "target" can't convert it to visual why?
  • Shrike
    Shrike almost 14 years
    Dan, do you know how to emulate pressing a key with a modifier (ctrl/alt/shift) ? Particulary I need to simulate InputBinding:m_shell.InputBindings.Add( new KeyBinding(m_command, Key.Insert, ModifierKeys.Control | ModifierKeys.Alt));
  • Smith
    Smith over 12 years
    @RayBurns does this apply to htmlelement in webbrowser control too?
  • OscarRyz
    OscarRyz about 12 years
    About the target issue, I worked it out by using Keyboard.PrimaryDevice.ActiveSource see stackoverflow.com/questions/10820990/…
  • code4life
    code4life almost 12 years
    @RayBurns: thanks for the tip! Just one note, your code doesn't compile in VS 2010. Maybe can update with alternative code from @OscarRyz?
  • Sergey
    Sergey almost 12 years
    Suitable, if your window will be on top. It partially solved my situation, thanks!
  • user1123236
    user1123236 almost 11 years
    An addition to Rajesh's answer, if you want to do this in mobile platform, you must import "coredll.ddl"
  • ANeves
    ANeves over 9 years
    This answer is very good, but it cannot be used to send a key with a modifier, as @Shrike noted. (E.g. Ctrl+C.)
  • user1234433222
    user1234433222 about 8 years
    This works very well, however i haven't been able to find how to make this work with a combination of keys,
  • Ravid Goldenberg
    Ravid Goldenberg about 8 years
    When you say combination of keys do you mean like CTRL-C?
  • user1234433222
    user1234433222 about 8 years
    yeah or even if you wanted a console application to go full screen eg Alt-Enter, i know you can use F11 to enter full screen but it would be nice to see if Alt-Enter would work :)
  • Ravid Goldenberg
    Ravid Goldenberg about 8 years
    Well you can do that, although I haven't tried it, just use inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CON‌​TROL, VirtualKeyCode.VK_C);
  • escape-llc
    escape-llc almost 6 years
    only seems to work if you have event handlers hooked up to the target.
  • Starwave
    Starwave over 3 years
    This only works if you are targeting your own application. If you switch to, let's say, notepad, then this keypress won't execute there.
  • RoySeberg
    RoySeberg over 2 years
    My simulated key doesn't stay down and automatically repeat as does the actual keyboard key: it does only one press. How do I get it to stay down and keep repeating automatically until I tell it to go back up?