[英]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.