我在我的 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/