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. WhiteOct 29, 2009 at 18:54
-
I think you'd have to step into unmanaged code in order to simulate a 'real' keypress.– Jonas BOct 29, 2009 at 18:58
-
Yes, I just need the event to fire.– Dan VogelOct 30, 2009 at 17:00
-
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 4, 2012 at 1:52
-
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 VogelAug 6, 2012 at 18:26
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.
-
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. Oct 30, 2009 at 17:27
-
29when I tried the first code of keydown I got error in "target" can't convert it to visual why?– kartalAug 26, 2010 at 7: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));– ShrikeSep 10, 2010 at 14:36
-
15About the target issue, I worked it out by using
Keyboard.PrimaryDevice.ActiveSource
see stackoverflow.com/questions/10820990/…– OscarRyzMay 30, 2012 at 17:26 -
4This answer is very good, but it cannot be used to send a key with a modifier, as @Shrike noted. (E.g.
Ctrl+C
.)– ANevesJan 23, 2015 at 17:17
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
-
Suitable, if your window will be on top. It partially solved my situation, thanks!– SergeySep 18, 2012 at 17:54
-
An addition to Rajesh's answer, if you want to do this in mobile platform, you must import "coredll.ddl" Jul 10, 2013 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); Nov 23, 2022 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.
-
5I 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. Oct 30, 2009 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. Oct 30, 2009 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.
-
This works very well, however i haven't been able to find how to make this work with a combination of keys, May 6, 2016 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 :) May 7, 2016 at 18:50
-
1Well you can do that, although I haven't tried it, just use inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_C); May 7, 2016 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? Mar 9, 2022 at 15:56