4

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"...

svick
  • 236,525
  • 50
  • 385
  • 514
Melursus
  • 10,328
  • 19
  • 69
  • 103
  • I don't understand what you're trying to do. That isn't valid C# code. –  Jun 27 '11 at 20:16
  • 6
    For those (like me) that need to look this up: http://msdn.microsoft.com/en-us/library/system.windows.input.keyeventargs.key.aspx – Marc Gravell Jun 27 '11 at 20:17
  • 2
    @Inuyasha he's trying to find a method that will return the standard key-cap / glyph / symbol for a key, rather than the **enum** name, which will be more verbose. The intent is clear, IMO. – Marc Gravell Jun 27 '11 at 20:18
  • This is probably a duplicate of http://stackoverflow.com/questions/855047/how-do-you-convert-a-system-windows-input-keyeventargs-key-to-a-char which has an answer that looks promising – Rebecca Scott Jun 28 '11 at 09:10
  • @RebeccaScott Seems like the opposite. Still, conversion from key code to string [has been posted (and answered) before](https://stackoverflow.com/q/6929275/395685) – Nyerguds Feb 25 '21 at 22:39

5 Answers5

8

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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Why not use `Dictionary`? – svick Jun 27 '11 at 20:22
  • @svick: I was making that change while you said it :) – Ry- Jun 27 '11 at 20:22
  • This is probably better than a `switch-case` ... I think I'd get shot for suggesting a `Dictionary` – IAbstract Jun 27 '11 at 20:22
  • @Svick: I have suggested using an enum as the TKey before and I was told "bad idea" by several people ... although I didn't understand why it would be – IAbstract Jun 27 '11 at 20:24
  • @IAbstract, maybe that's because in some cases, ordinary class with static properties (like `Key.Subtract`) instead of enum members and instance properties (like `Key.Char`) instead of what you want to put in the array would be better. But that's not possible here, since we're not in a position to change `Key`. – svick Jun 27 '11 at 20:32
  • How can I handle special stated key. Like RightShift + 9? – Melursus Jun 28 '11 at 12:40
  • @Melursus: Check for `(e.ModifierKey & Keys.RightShift) == Keys.RightShift && e.KeyCode == Keys.D9`. – Ry- Jun 28 '11 at 15:44
4

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

2

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;
Steve Czetty
  • 6,147
  • 9
  • 39
  • 48
osos95
  • 169
  • 1
  • 10
  • You can, but it won´t help. A bijective mapping between Key-Enum value and character set value is simply not possible, due to collisions (Key.NumPad0 and Key.D0 have to have different values, but should both result in character '0'). In fact, the entire mapping of the Key-Enum is different to any character set. Just press F12 in Visual Studio on the Key-Enum and convince yourself – 0xDEADBEEF Jul 29 '15 at 08:16
  • He wanted to get the value to the Keys object as a string, not the opposite, so I can see no problem here @0xDEADBEEF – osos95 Jul 29 '15 at 14:09
1

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();
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
-1

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

boca
  • 2,352
  • 19
  • 21
  • Very interesting article. Do you know if this technique can be applied to an existing type? –  Jun 27 '11 at 20:21
  • Definitely. You just have to have access tp the source to add the Description attribute – boca Jun 27 '11 at 20:27
  • Ahh. This enumeration is part of .NET though :( –  Jun 27 '11 at 20:28