触发键盘按键事件,而无需按键盘上的键 [英] Trigger a keyboard key press event without pressing the key from keyboard

查看:215
本文介绍了触发键盘按键事件,而无需按键盘上的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不从键盘上按下键的情况下触发按键事件?我尝试了此处中的解决方案,但是我出现以下异常:

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:

与之匹配的最佳重载方法 'System.Windows.PresentationSource.FromVisual(System.Windows.Media.Visual)' 有一些无效的参数.

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

考虑 Shift + A 包含键盘上的2个按键事件,如何在不按键盘的情况下进行操作?(让我们在按钮上单击时在文本框中打印大写字母A)

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)

我的代码

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 });

推荐答案

System.Windows.Forms.SendKeys.Send()为我完成了窍门.

有关高级说明和可用代码列表,请参考

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

例如,要发送 Shift + A ,我使用了SendKeys.Send("+(a)").

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

这篇关于触发键盘按键事件,而无需按键盘上的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆