How can I programmatically create an event that would simulate a key being pressed on the keyboard?
-
6Do you just need the event to fire? – Daniel A. White Oct 29 '09 at 18:54
-
I think you'd have to step into unmanaged code in order to simulate a 'real' keypress. – Jonas B Oct 29 '09 at 18:58
-
Yes, I just need the event to fire. – Dan Vogel Oct 30 '09 at 17:00
-
No @EdS. there are perfectly valid reasons for this, such as for developing a keypad. – GONeale Jul 04 '12 at 01:01
-
1@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. Jul 04 '12 at 01:52
-
@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 :) – Ed S. Jul 04 '12 at 01:53
-
6@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. – Dan Vogel Aug 06 '12 at 18:26
-
@EdS. Also it could be used to tests, to simulate user's input. – Karolis Kajenas Dec 31 '15 at 13:30
5 Answers
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.

- 3,249
- 3
- 24
- 42

- 62,163
- 12
- 140
- 141
-
1I 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. – Dan Vogel Oct 30 '09 at 17:27
-
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 Oct 30 '09 at 20:17
-
I edited my answer and added details on how to use TextInput events. – Ray Burns Oct 30 '09 at 20:26
-
29when I tried the first code of keydown I got error in "target" can't convert it to visual why? – kartal Aug 26 '10 at 07:12
-
3Dan, 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)); – Shrike Sep 10 '10 at 14:36
-
-
15About the _target_ issue, I worked it out by using `Keyboard.PrimaryDevice.ActiveSource` see http://stackoverflow.com/questions/10820990/how-to-create-a-keyeventargs-object-in-wpf-related-to-a-so-answer/10821212#10821212 – OscarRyz May 30 '12 at 17:26
-
@RayBurns: thanks for the tip! Just one note, your code doesn't compile in VS 2010. Maybe can update with alternative code from @OscarRyz? – code4life Sep 12 '12 at 20:34
-
4This answer is very good, but it cannot be used to send a key with a modifier, as @Shrike noted. (E.g. `Ctrl+C`.) – ANeves Jan 23 '15 at 17:17
-
only seems to work if you have event handlers hooked up to the target. – escape-llc Sep 05 '18 at 14:33
-
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. – Starwave Jan 24 '21 at 18:48
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

- 886
- 1
- 9
- 31

- 1,911
- 1
- 22
- 19
-
Suitable, if your window will be on top. It partially solved my situation, thanks! – Sergey Sep 18 '12 at 17:54
-
An addition to Rajesh's answer, if you want to do this in mobile platform, you must import "coredll.ddl" – user1123236 Jul 10 '13 at 14:43
-
This works great on WPF! But i want to press Shift+Enter ?? keybd_event((byte)VK_LSHIFT, 0, KEYEVENTF_EXTENDEDKEY | 0, 0); – Wolfgang Schorge Nov 23 '22 at 17:15
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.

- 59,888
- 27
- 145
- 179
-
4I 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 Oct 30 '09 at 17:07
-
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. – Michael Petrotta Oct 30 '09 at 20:14
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:
Install the package, can be done or from the NuGet package manager or from the package manager console like:
Install-Package InputSimulator
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.

- 2,119
- 4
- 39
- 59
-
This works very well, however i haven't been able to find how to make this work with a combination of keys, – user1234433222 May 06 '16 at 18:39
-
-
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 :) – user1234433222 May 07 '16 at 18:50
-
1Well you can do that, although I haven't tried it, just use inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_C); – Ravid Goldenberg May 07 '16 at 19:21
-
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? – RoySeberg Mar 09 '22 at 15:56
Windows SendMessage API with send WM_KEYDOWN.

- 30,738
- 21
- 105
- 131

- 5,725
- 6
- 52
- 76