Trigger a keyboard key press event without pressin

2019-01-17 23:53发布

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条回答
Juvenile、少年°
2楼-- · 2019-01-18 00:35

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)
{

}
查看更多
时光不老,我们不散
3楼-- · 2019-01-18 00:39

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

查看更多
虎瘦雄心在
4楼-- · 2019-01-18 00:40

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

查看更多
登录 后发表回答