代码之家  ›  专栏  ›  技术社区  ›  stiank81

如何模拟WPF文本框的文本输入?

  •  13
  • stiank81  · 技术社区  · 16 年前

    我想模拟用户对WPF文本框的输入。我想输入一个字符,以便触发onpreviewTimePut事件。我尝试通过Text属性设置文本,但这没有触发事件:

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

    我能以某种方式显式触发事件吗?

    2 回复  |  直到 16 年前
        1
  •  22
  •   Community Mohan Dere    9 年前

    看到答案了吗 How can I programmatically generate keypress events in C#? 有关如何模拟输入事件的详细说明。

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

    这将引发PreviewTimePut事件,然后引发TextInput事件并更改文本。

        2
  •  4
  •   Den    16 年前

    另一种方法是使用WinAPI,SendMessage是特定的:

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

    当焦点在文本框上时,可以这样称呼它:

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

    H

    推荐文章