I am attempting to simulate keyboard input to a WPF TextBox control (the reasons for doing this are outside the scope of this question). 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. 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.