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

两盒软妹~` 提交于 2019-11-28 08:41:17
ridoy

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

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

}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!