将 System.Windows.Input.KeyEventArgs 键转换为 char
我需要将事件参数作为 char
获取,但是当我尝试转换 Key 枚举时,我得到的字母和符号与传入的字母和符号完全不同。
如何正确地将 Key 转换为 char?
这是我尝试过的
ObserveKeyStroke(this, new ObervableKeyStrokeEvent((char)((KeyEventArgs)e.StagingItem.Input).Key));
编辑:我在参数上也没有 KeyCode 属性。 我从 InputManager.Current.PreNotifyInput 事件获取它们。
I need to get the event args as a char
, but when I try casting the Key enum I get completely different letters and symbols than what was passed in.
How do you properly convert the Key to a char?
This is what I've tried
ObserveKeyStroke(this, new ObervableKeyStrokeEvent((char)((KeyEventArgs)e.StagingItem.Input).Key));
Edit: I also don't have the KeyCode property on the args. I'm getting them from the InputManager.Current.PreNotifyInput event.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在您的 PreNotifyInput 处理程序中,尝试如下操作:
它会针对不同的路由事件引发多次,因此您可能需要过滤特定的事件。
Inside your PreNotifyInput handler, try something like this:
It raises multiple times for the different routed events, so you may want to filter for a particular one.
请参阅如何转换等效 System.Windows.Input.Key Enum 值中的字符?
请改用
KeyInterop.VirtualKeyFromKey
。See How to convert a character in to equivalent System.Windows.Input.Key Enum value?
Use
KeyInterop.VirtualKeyFromKey
instead.这需要一点时间来适应,但您可以只使用键值本身。 如果您试图将输入限制为字母数字,甚至可能有点额外,下面的代码可能会有所帮助。
It takes a little getting used to, but you can just use the key values themselves. If you're trying to limit input to alphanumerics and maybe a little extra, the code below may help.
这对我有用:
根据上一个条目,我发现在 WPF 中没有这样的事件
PreNotifyInput
,但我找到了等效的PreviewTextInput
首先,我尝试使用
RegExp
,但我无法使其工作,然后我使用一个简单的indexOf
。That work for me:
Based on the last entry i found that in WPF there is no such event
PreNotifyInput
, but i found and equivalentPreviewTextInput
First I try with a
RegExp
, but I cant make it work, then I use a simpleindexOf
.我知道这已经很旧了,但似乎没有一个答案能够真正回答这个问题。 返回不同字符的原因是,当您尝试将其转换为
char
时,您正在将枚举值转换为“char”。 但是:效果很好。 以字符串形式返回按下的键。 然后你检查长度。 如果它是 == 1 那么它是一个字符、数字或符号。 如果它大于 1,则它是一个特殊密钥。
如果您只想要 char,则可以执行
keyPressed[0];
这就是我的做法。
I know this is old, but none of the answers seem to actually answer the question. The reason a different char is coming back is because when you just try to cast it to a
char
you are casting the enum value to a 'char'. However:Works great. Returns the key pressed as a string. Then you check the length. If it's == 1 then it's a char, number or symbol. If it's greater than 1 it's a special key.
If you just want the char you can then do
keyPressed[0];
This is how I do it.