How do I convert a "Keys" enum value to an "int" character in C#?

Andy Stampor picture Andy Stampor · Apr 20, 2009 · Viewed 28.1k times · Source

This seems like something that should be easy, but I am having a tough time figuring out what needs to happen here.

In the "KeyDown" eventhandler, if the "e.KeyValue" is a number, I want to treat it as a number and store it as an int. So, if I hit "8" on the number pad, I don't want "Numpad8" I want the int value 8 that I can add or subtract or whatever.

So, how do I convert from the KeyValue to an int?

Answer

Tommi Forsström picture Tommi Forsström · Apr 20, 2009

I'd go with this solution:

int value = -1;
if (e.KeyValue >= ((int) Keys.NumPad0) && e.KeyValue <= ((int) Keys.NumPad9)) { // numpad
    value = e.KeyValue - ((int) Keys.NumPad0);
} else if (e.KeyValue >= ((int) Keys.D0) && e.KeyValue <= ((int) Keys.D9)) { // regular numbers
    value = e.KeyValue - ((int) Keys.D0);
}

...if the point was to get the numeric value of the label of they key that was punched in.