8
votes

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 });
3
have you tried the sendkeys example in your link? - RandomUs1r
@RandomUs1r,Yes i tried,but a need a target to send that key.If a have 10 textboxes in a form,then what should be the criteria?I want to write A where there is current focus for which i used Keyboard.FocusedElement in above code.Do you have any idea? - ridoy
I would use the focusmanager class instead: msdn.microsoft.com/en-us/library/… . On a higher level though, I would probably try to implement something like this in jQuery. - RandomUs1r
@RandomUs1r jQuery... in WPF?!? - ANeves

3 Answers

11
votes

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)").

2
votes

You need to cast to Visual :

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((Visual)target), 0, key) { RoutedEvent = routedEvent });

You could also specify that your target is a specific textbox for example :

var target = textBox1;    // Target element

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 :

private void textBox1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{

}
0
votes

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