首页 > 解决方案 > WPF将密钥发送到文本框

问题描述

我正在使用虚拟键盘,但我很难发送按键。什么都没有发生,除非我将它们硬添加到文本框中。这是我的代码

  public static void Send(Key key)
    { //Found online
                var e = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, key)
                {
                    RoutedEvent = Keyboard.KeyDownEvent
                };
                InputManager.Current.ProcessInput(e);
    }


  private void ClickOnKey(object sender, RoutedEventArgs e)
    {
        CustomButton cb = sender as CustomButton;
        string text = cb.text;
        Console.WriteLine(text);
        element_to_focus.Focus(); //The textbox
        Send(translate_string_to_key(text));
     }

标签: wpfkeyboard-events

解决方案


ProcessInput似乎只会引发适当的键相关事件,但不会实际修改文本。

如果您真的想模拟按键,则需要利用 p/invoke 并使用 SendInput. 幸运的是,有人已经为我们完成了 p/invoke 工作并提供了他们的工作:
https ://archive.codeplex.com/?p=inputsimulator

它也可以作为 NuGet 包提供(我找到了两个版本):
https://www.nuget.org/packages/InputSimulator/
https://www.nuget.org/packages/InputSimulatorPlus/


推荐阅读