c# - WPF、PreviewKeyDown 事件和下划线字符

标签 c# wpf

我在我的 WPF 组件中使用 PreviewKeyDown 事件捕获按键命中。我需要区分正在键入的字符:字母、数字、下划线和其他任何字符。

字母和数字工作正常(只需将 KeyEventArgs 对象的 Key 属性转换为字符串并使用该字符串的字符 0),但这不适用于下划线。

它的 ToString 值取决于本地化的键盘设置(它在 EN/US 键盘上显示为“OemMinus”,在 CZ/QWERTY 键盘上显示为“OemQuestion”)。

那么,如果 PreviewKeyDown 事件中键入的字符是下划线,我如何才能可靠地发现?

感谢您的帮助

最佳答案

更新:

这有点乱,但经过一些重构后可能会对您有所帮助。 我使用预览事件捕获文本并强制发送我想要的 key ;我忽略了预览处理程序中的所有其他键。我确实从 KeyDown 切换到 KeyUp 以使预览事件首先触发。我使用 _clearNext 标志来跳过/清除按键事件。

在 XAML 中

<Window x:Class="EmployeeNavigator.Views.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    PreviewTextInput="Window_PreviewTextInput"
    Keyup="Window_KeyUp"
    Height="400" 
    Width="600"
    MinWidth="600">
</Window>

代码隐藏检测和处理 _

  private bool _clearNext = false;
  private void Window_KeyUp(object sender, KeyEventArgs e)
  {
     if ( _clearNext )
     {
        _clearNext = false;
        e.Handled = true;
     }
     else if (e.Key == Key.OemMinus)
     {
        e.Handled = true;
     }
     else if (e.Key == Key.OemQuestion)
     {
        e.Handled = true;
     }
  }

  private void Window_PreviewTextInput(object sender, TextCompositionEventArgs e)
  {
     if (e.Text.Equals("_"))
     {
        KeyEventArgs args = new KeyEventArgs(Keyboard.PrimaryDevice,
           Keyboard.PrimaryDevice.ActiveSource, 0, Key.OemMinus);
        args.RoutedEvent = Keyboard.KeyUpEvent;
        InputManager.Current.ProcessInput(args);
        e.Handled = true;
        _clearNext = true;
     }
     else if (e.Text.Equals("?"))
     {
        KeyEventArgs args = new KeyEventArgs(Keyboard.PrimaryDevice,
           Keyboard.PrimaryDevice.ActiveSource, 0, Key.OemQuestion);
        args.RoutedEvent = Keyboard.KeyUpEvent;
        InputManager.Current.ProcessInput(args);
        e.Handled = true;
        _clearNext = true;
     }
  }

我要补充的是一定有更好的方法。

关于c# - WPF、PreviewKeyDown 事件和下划线字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2924928/

相关文章:

c# - 无法从 Powershell 3.0 调用 C# 类

java - 在 Unity 5 中使用 Hazelcast 客户端

c# - 将 ContentControl *放在 * WPF DataTemplate 中?

c# - 如何将 ObservableConcurrentDictionary 绑定(bind)到 WPF TreeView

wpf - 使 WPF 图像加载异步

wpf - VisualStateManager 无法为 ThicknessAnimations 生成过渡

c# - 访问按钮内的 TextBlock.Text

c# - 在 c# 中使用 HttpWebRequest 发送 base64 字符串将 "+"转换为空白问题

c# - 限制 CosmosDB 查询的 1000 条记录

c# - 如何在另一个切换为真时将切换更改为假