我正在处理窗口上的PreviewTextInput事件,以处理来自磁卡读取器的滑动。我在窗口上处理事件,因此,重点放在单个控件上无关紧要。
一旦处理程序确定开始滑动(输入了'%'或';'字符),它将处理所有事件,直到滑动完成。该系统通常运行良好,但有一些重要的异常(exception):
当从阅读器输入空格字符(可能还有\ n字符)时,它们不会由PreviewTextInput处理,而是直接发送到要聚焦的控件中。奇怪的是,处理程序确实接收到\ r个字符。这会导致不良行为。
我想要的是一种在窗口级别捕获所有关键事件的方法,并且如果我愿意,有机会对其进行处理。我尝试了PreviewKeyDown,发现使用它以及从中获取char值有点麻烦。 PreviewTextInput更好,因为我可以简单地读取Text属性。
有没有原因PreviewTextInput无法处理某些字符?是否有任何可比较的方法来获取所有事件,包括空格?
最佳答案
我在this WPF forum question中找到了某种解释:
Because some IMEs will treat whitespace keystroke as part of the text composition process, that's why it eats up by Avalon to report correct composited text through TextInput event.
以及来自MSDN documentation of the TextInput event的更多信息:
... For keyboard input, WPF first sends the appropriate KeyDown/KeyUp events. If those events are not handled and the key is textual (rather than a control key such as directional arrows or function keys), then a TextInput event is raised. There is not always a simple one-to-one mapping between KeyDown/KeyUp and TextInput events because multiple keystrokes can generate a single character of text input and single keystrokes can generate multi-character strings. This is especially true for languages such as Chinese, Japanese, and Korean which use Input Method Editors (IMEs) to generate the thousands of possible characters in their corresponding alphabets.
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.
顺便说一句,这是两个相关的问题:
关于wpf - 为什么PreviewTextInput不处理空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7971559/