Trigger a keyboard key press event without pressing the key from keyboard

ridoy picture ridoy · Mar 22, 2013 · Viewed 33.4k times · Source

How can I trigger a key press event without pressing the key from Keyboard? I tried with the solution from here, but I got the following exception:

The best overloaded method match for 'System.Windows.PresentationSource.FromVisual(System.Windows.Media.Visual)' has some invalid arguments.

Consider Shift+A contains 2 key press event from keyboard,how can I do it without keyboard pressing?(let, just print capital A in a textbox on a button click)

My code

var key = Key.A;                    // Key to send
var target = Keyboard.FocusedElement;    // Target element
var routedEvent = Keyboard.KeyDownEvent; // Event to send

target.RaiseEvent(new System.Windows.Input.KeyEventArgs(Keyboard.PrimaryDevice, System.Windows.PresentationSource.FromVisual(target), 0, key) { RoutedEvent = routedEvent });

Answer

ridoy picture ridoy · Mar 22, 2013

System.Windows.Forms.SendKeys.Send() has done the trick for me.

For advanced instructions and the list of available codes, consult the docs for the method.

For example, to send Shift+A I used SendKeys.Send("+(a)").