Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I simulate Text input to a WPF TextBox?

Tags:

.net

wpf

textbox

I want to simulate user input to a WPF TextBox. I want to input a character such that the OnPreviewTextInput event is triggered. I tried setting the Text through the Text property, but this didn't trigger the event:

public void SomeFunction()
{
    var textBox = new TextBox();
    textBox.Text = "A";                     
}

Can I trigger the event explicitly somehow?

like image 714
stiank81 Avatar asked Aug 04 '10 10:08

stiank81


2 Answers

See the answer to How can I programmatically generate keypress events in C#? for a good description of how to simulate input events.

You could also do:

TextCompositionManager.StartComposition(
    new TextComposition(InputManager.Current, textBox, "A"));

This will raise the PreviewTextInput event and then raise the TextInput event and change the text.

like image 174
Quartermeister Avatar answered Sep 27 '22 22:09

Quartermeister


Another way to do this would be by using WinAPI, SendMessage to be specific:

[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

Then call it this way, when the focus is on the TextBox:

SendMessage(new WindowInteropHelper(this).Handle, 0x0102, 72, 0)

0x0102 is the constant value for WM_CHAR and 72 is the keycode for H (you can change this accordingly).

like image 25
Den Delimarsky Avatar answered Sep 27 '22 21:09

Den Delimarsky