Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key (enum) to string

Tags:

c#

enums

key

How can I convert a Key (Key in KeyEventArgs) to a string.

For example, if the user enter "-" :

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

What I want is to get "-" for result, not "Substract"...

like image 964
Melursus Avatar asked Dec 09 '22 07:12

Melursus


1 Answers

Use a Dictionary<TKey, TValue>:

Class-level:

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()] instead.

Edit: Actually, for more 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] instead.

like image 56
Ry- Avatar answered Dec 25 '22 09:12

Ry-