本文介绍了为什么 PreviewTextInput 不处理空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理我的窗口上的 PreviewTextInput 事件以处理来自磁卡读卡器的滑动.我处理窗口上的事件,因此关注哪个单独的控件并不重要.

I am handling the PreviewTextInput event on my window to handle swipes from a magnetic card reader. I handle the event on the window, so that it does not matter which individual control is focused.

一旦处理程序确定滑动已开始(输入%"或;"字符),它将处理所有事件,直到滑动完成.该系统通常运行良好,但有一些重要的例外:

Once the handler determines a swipe has started (a '%' or ';' character is input), it handles all events until the swipe is finished. This system generally works quite nicely, with a few important exceptions:

当从阅读器输入空格字符(也可能是 字符)时,它们不会由 PreviewTextInput 处理,而是直接发送到任何焦点控件.奇怪的是,处理程序确实收到了 字符.这会导致不良行为.

When a space character (and possibly a character) are input from the reader, they are not handled by PreviewTextInput, but are sent directly into whatever control is focused. Oddly enough, the handler does receive characters. This causes undesired behavior.

我想要的是一种在窗口级别捕获所有关键事件的方法,并且如果我愿意的话有机会处理它们.我试过 PreviewKeyDown 并发现它使用起来有点麻烦,并从中获取 char 值.PreviewTextInput 更好,因为我可以简单地读取 Text 属性.

What I want is a way to capture all key events at the window level, and have an opportunity to handle them if I want to. I have tried PreviewKeyDown and found it a bit cumbersome to use, and to get char values from. PreviewTextInput is much nicer because I can simply read the Text property.

PreviewTextInput 不处理某些字符是否有原因?有没有类似的方法来获取所有事件,包括空格?

Is there a reason PreviewTextInput does not handle certain characters? Is there any comparable method to get all events, including spaces?

推荐答案

我在 这个 WPF 论坛问题:

因为某些 IME 会将空格键击视为文本合成过程的一部分,这就是为什么 Avalon 会通过 TextInput 事件报告正确的合成文本.

以及来自 TextInput 事件的 MSDN 文档的更多信息:

... 对于键盘输入,WPF 首先发送适当的 KeyDown/KeyUp 事件.如果未处理这些事件并且键是文本键(而不是方向箭头或功能键等控制键),则会引发 TextInput 事件.KeyDown/KeyUp 和 TextInput 事件之间并不总是存在简单的一对一映射,因为多次击键可以生成文本输入的单个字符,而单次击键可以生成多字符串.对于使用输入法编辑器 (IME) 以相应字母表生成数千个可能字符的语言(例如中文、日文和韩文)来说尤其如此.

当 WPF 发送 KeyUp/KeyDown 事件时,如果击键可能成为 TextInput 事件的一部分(例如,如果按下 ALT+S),则将 Key 设置为 Key.System.这允许 KeyDown 事件处理程序中的代码检查 Key.System,如果找到,则将处理留给随后引发的 TextInput 事件的处理程序.在这些情况下,TextCompositionEventArgs 参数的各种属性可用于确定原始击键.同样,如果 IME 处于活动状态,则 Key 的值为 Key.ImeProcessed,而 ImeProcessedKey 给出原始击键或击键.

When WPF sends a KeyUp/KeyDown event, Key is set to Key.System if the keystrokes could become part of a TextInput event (if ALT+S is pressed, for example). This allows code in a KeyDown event handler to check for Key.System and, if found, leave processing for the handler of the subsequently raised TextInput event. In these cases, the various properties of the TextCompositionEventArgs argument can be used to determine the original keystrokes. Similarly, if an IME is active, Key has the value of Key.ImeProcessed, and ImeProcessedKey gives the original keystroke or keystrokes.

顺便说一句,这里有两个相关的问题:

BTW, Here are two related questions:

这篇关于为什么 PreviewTextInput 不处理空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 16:23