[英]KeyDown event sent to WPF TextBox does not trigger text input
I am attempting to simulate keyboard input to a WPF TextBox control (the reasons for doing this are outside the scope of this question). 我正在尝试模拟向WPF TextBox控件的键盘输入(执行此操作的原因不在此问题的范围之内)。 However, I am having difficulty in getting text to appear.
但是,我很难让文字出现。
I've made a simple WPF application containing a single button and a single textbox, and I want to simulate a keyboard press when clicking the button, causing a single character of text (the letter "A") to be typed into the textbox. 我已经制作了一个简单的WPF应用程序,其中包含一个按钮和一个文本框,并且我想模拟单击按钮时的键盘按压,从而导致在文本框中键入单个文本字符(字母“ A”)。 This is what I have so far:
这是我到目前为止的内容:
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 });
}
I have tried attaching event handlers to the textbox, and I can see and verify that the event are being received by the textbox. 我尝试将事件处理程序附加到文本框,并且可以看到并验证该文本框正在接收事件。 However, none of them actually make any text appear.
但是,它们实际上都不会显示任何文本。
How can I go about triggering text input by raising an event? 我该如何通过引发事件来触发文本输入?
Any help is much appreciated, thanks. 非常感谢任何帮助,谢谢。
Have you tried getting the control's AutomationPeer, eg: 您是否尝试过获取控件的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.