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 });
You need to cast to
Visual
:You could also specify that your target is a specific textbox for example :
What the code actually does is trigger the keydown event for a specific element. So it makes sense to have a keydown handler for it :
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)")
.Easy and reliable way to simulate the keyboard event is to use the keybd_event api
You can get reference to it here
http://www.pinvoke.net/default.aspx/user32.keybd_event
There are further articles on it here
http://www.codeproject.com/Articles/7305/Keyboard-Events-Simulation-using-keybd_event-funct