How do I simulate Text input to a WPF TextBox?

后端 未结 2 414
半阙折子戏
半阙折子戏 2021-02-07 15:05

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 proper

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 15:35

    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).

提交回复
热议问题