programmer1490 programmer1490 - 3 months ago 102
C# Question

Convert keycode to char/string

I'm trying to convert

System.Windows.Forms.Keys
to string/char using :

KeysConverter converter = new KeysConverter();
string text = converter.ConvertToString(keyCode);
Console.WriteLine(text);


But it returned "OemPeriod" for "." and "Oemcomma" for ",". Is there any way to get the exact character?

Answer

Those are the correct and expected names for the comma and period keys on your keyboard. You can see that clearly from the documentation. The KeysConverter class is behaving as expected and as designed.

If you want to come up with a different name for those keys you can detect them and substitute the name that you desire to use. For instance:

string name;
switch (e.KeyCode)
{
    case Keys.Oemcomma:
        name = "Comma";
        break;
    case Keys.OemPeriod:
        name = "Period";
        break;
    default:
        name = (new KeysConverter()).ConvertToString(e.KeyCode);
        break;
}
Comments