Key (enumeration) to the line

How to convert a key (key in KeyEventArgs) to a string.

For example, if the user enters "-":

e.Key.ToString() = "Subtract" new KeyConverter().ConvertToString(e.Key) = "Subtract" 

I want to get a "-" for the result, not "Substract" ...

+4
source share
5 answers

Use Dictionary<TKey, TValue> :

Level class:

 private readonly Dictionary<string, string> operations = new Dictionary<string, string>; public ClassName() { // put in constructor... operations.Add("Subtract", "-"); // etc. } 

In your method, just use operations[e.Key.ToString()] .

Edit: Actually, for greater efficiency:

 private readonly Dictionary<System.Windows.Input.Key, char> operations = new Dictionary<System.Windows.Input.Key, char>; public ClassName() { // put in constructor... operations.Add(System.Windows.Input.Key.Subtract, '-'); // etc. } 

In your method, just use operations[e.Key] .

+7
source

The message generates a โ€œsubtractโ€ because Key returns a KeyCode , an enumeration of which Subtract is a member.

Without an explicit display, it is impossible to extract "-" from this. (For explicit matching, use the switch if / else, a dictionary, or whatever :-)

To get a character, not a key code, maybe use another event?

Happy coding

+4
source

Well, you can use translation if you want to convert the Keys object to a string object, for example:

 string key = ((char)e.Key).ToString(); 

Just remember that a Keys object can accept a char cast, so we can apply the resulting char object to a string object. If you just want to add it to the char object, just remove that shit and do this:

 char key = (char)e.key; 
+2
source

You can use this function:

 public static string KeycodeToChar(int keyCode) { Keys key = (Keys)keyCode; switch (key) { case Keys.Add: return "+"; case Keys.Subtract: return "-"; //etc... default: return key.ToString(); } } 
+1
source

You can use the Description attributes and then override ToString () to get a "-" instead of a name. Here is an article explaining how to do this http://blogs.msdn.com/b/abhinaba/archive/2005/10/20/c-enum-and-overriding-tostring-on-it.aspx

-1
source

All Articles