![](/img/trans.png)
[英]How can I get the text from the TextBox_KeyDown event? WPF C#
[英]KeyDown event sent to WPF TextBox does not trigger text input
我正在尝试模拟向WPF TextBox控件的键盘输入(执行此操作的原因不在此问题的范围之内)。 但是,我很难让文字出现。
我已经制作了一个简单的WPF应用程序,其中包含一个按钮和一个文本框,并且我想模拟单击按钮时的键盘按压,从而导致在文本框中键入单个文本字符(字母“ A”)。 这是我到目前为止的内容:
private void button_Click(object sender, RoutedEventArgs e)
{
var key = Key.A;
var target = textBox1; // Keyboard.FocusedElement;
// None of these actually induce text to appear in the textbox
target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual((Visual)target), 0, key) { RoutedEvent = Keyboard.PreviewKeyDownEvent });
target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual((Visual)target), 0, key) { RoutedEvent = Keyboard.PreviewKeyUpEvent });
target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual((Visual)target), 0, key) { RoutedEvent = Keyboard.KeyDownEvent });
target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual((Visual)target), 0, key) { RoutedEvent = Keyboard.KeyUpEvent });
}
我尝试将事件处理程序附加到文本框,并且可以看到并验证该文本框正在接收事件。 但是,它们实际上都不会显示任何文本。
我该如何通过引发事件来触发文本输入?
非常感谢任何帮助,谢谢。
您是否尝试过获取控件的AutomationPeer,例如:
TextBox tb;
TextBoxAutomationPeer tbap = new TextBoxAutomationPeer(tb);
IValueProvider vp = tbap.GetPattern(PatternInterface.Value) as IValueProvider;
vp.SetValue("Your text here.");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.