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"...
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"...
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.
The post generates "Subtract" because Key
returns a KeyCode
, an enumeration, of which Subtract
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
Well, you can use a cast if you want to convert a Keys object to a string object, like this:
string key = ((char)e.Key).ToString();
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:
char key = (char)e.key;
You could use a function like this:
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();
}
}
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