c# - 在 WPF 中模拟按键

标签 c# .net wpf input touch

我正在为 WPF 触控应用开发屏幕数字键盘。这将出现在 Popup 中。当一个按钮被按下时,它应该向应用程序发送一个键击,使它看起来就像用户正在输入一个 TextBox。这是我的代码:

// 'key' is set beforehand
InputManager.Current.ProcessInput(new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, Environment.TickCount, key) { RoutedEvent = Control.KeyDownEvent });

这在 Button.Click 事件处理程序中调用。

到目前为止只有 Key.Back 有效。所有数字键都不起作用,Key.Decimal 也不起作用。

编辑:我认为使用 SendKeys 可以解决问题,但它只是做同样的事情。

为什么我的数字按钮不起作用?我已验证正在传递正确的 Key

最佳答案

根据我们在评论中的讨论,我建议您考虑采用这样的方法。我不知道完整的要求,但拆分功能并使应用程序不那么单一始终是一个好方法!

首先,伪 UML 图应该是这样的:

Class depedendency diagram

您的三个函数将按如下方式实现(伪代码):

UserControl1.InsertCharacter(string character)
{
    textBox1.Text = textBox1.Text.Insert(textBox1.CaretIndex, character); 
    this.ValidateInput();
}

UserControl1.ValidateInput()
{
    // Perform validation
}

UserControl1.OnKeyDown()
{
    // Perform validation
    this.ValidateInput();
}

UserControl2.AppendCharacter(string clickedCharacter)
{
    this.userControl1.InsertCharacter(clickedCharacter); 
}

要像我提到的那样进一步将 UserControl2 与 UserControl1 分离,您可以使用事件模式,例如 .NET 事件或 EventAggregator。

关于c# - 在 WPF 中模拟按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9469068/

相关文章:

c# - Entity Framework 确保对象按顺序插入

asp.net - 如何在 GridView 中隐藏 TemplateField 列

c# - 如何在 WPF 中处理长时间运行的 "thread"?

c# - 围绕执行相同检查的多个 if 语句的代码重构 C# 问题

.net - 如何在 Windows Server 2008 的程序集中安装文件?

wpf - TabControl View 不会因模板更改而更新

c# - 如何复制现有列并将其插入到datagrid中?

c# - 同一类型的多个参数的编译时方法调用验证

c# - 通用映射器而不是有许多单独的映射器

c# - 如何在 Windows 8.1 上打开多个 Visual Studio 窗口?