字符串的键(枚举)
如何将键(KeyEventArgs 中的键)转换为字符串。
例如,如果用户输入“-”:
e.Key.ToString() = "Subtract"
new KeyConverter().ConvertToString(e.Key) = "Subtract"
我想要的是得到“-”结果,而不是“减去”...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
Dictionary
:类级别:
在您的方法中,只需使用
operations[e.Key.ToString()]
即可。编辑:实际上,为了提高效率:
在您的方法中,只需使用
operations[e.Key]
即可。Use a
Dictionary<TKey, TValue>
:Class-level:
In your method, just use
operations[e.Key.ToString()]
instead.Edit: Actually, for more efficiency:
In your method, just use
operations[e.Key]
instead.该帖子生成“Subtract”,因为
Key
返回一个KeyCode
,一个枚举,Subtract
是其中的成员。如果没有显式映射,就无法从中得到“-”。 (对于显式映射,请使用开关、if/else、字典或您喜欢的任何内容 :-)
要获取字符而不是键码,也许可以使用不同的事件?
快乐编码
The post generates "Subtract" because
Key
returns aKeyCode
, an enumeration, of whichSubtract
is a member.Without an explicit mapping, there is no way to get an "-" out of that. (For an explicit mapping, use a switch, if/else, Dictionary, or whatever you like :-)
To get a character and not a key code, perhaps use a different event?
Happy coding
那么,如果要将 Keys 对象转换为字符串对象,则可以使用强制转换,如下所示:
只需记住 Keys 对象可以接受 char 强制转换,因此我们可以将生成的 char 对象强制转换为字符串对象。
如果您只想将其附加到 char 对象,只需删除该废话,然后将其设置为如下所示:
Well, you can use a cast if you want to convert a Keys object to a string object, like this:
Just remember that a Keys object can accept a char cast, so we can cast the resultant char object to a string object.
If you want just to append it to a char object, just remove that crap, and make it like this:
你可以使用这样的函数:
You could use a function like this:
您可以使用 Description 属性,然后重写 ToString() 以获取“-”而不是名称。这是一篇文章,解释了如何执行此操作http://blogs.msdn.com/b/abhinaba/archive/2005/10/20/c-enum-and-overriding-tostring-on-it.aspx
You can use the Description attributes and then override ToString() to get "-" instead of the name. Here is an article that explains how to do it http://blogs.msdn.com/b/abhinaba/archive/2005/10/20/c-enum-and-overriding-tostring-on-it.aspx