我想模拟WPF TextBox的用户输入。我想输入一个字符,以便触发OnPreviewTextInput事件。我尝试通过Text属性设置Text,但这并没有触发事件:
public void SomeFunction()
{
var textBox = new TextBox();
textBox.Text = "A";
}
我可以以某种方式明确触发事件吗?
答案 0 :(得分:22)
有关如何模拟输入事件的详细说明,请参阅How can I programmatically generate keypress events in C#?的答案。
你也可以这样做:
TextCompositionManager.StartComposition(
new TextComposition(InputManager.Current, textBox, "A"));
这将引发PreviewTextInput事件,然后引发TextInput事件并更改文本。
答案 1 :(得分:4)
另一种方法是使用WinAPI,SendMessage是特定的:
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
然后在焦点位于TextBox上时以这种方式调用它:
SendMessage(new WindowInteropHelper(this).Handle, 0x0102, 72, 0)
0x0102是WM_CHAR的常量值,72是H
的键码(您可以相应地更改它)。