How to convert e.KeyChar to the actual character value when handling keyboard events?

All I want to do is get the actual character, which is pressed whenever the key for the event is entered.

The only option I see is e.KeyChar , which will give me a position, not the character itself.

What I want to do is limit the keypress values ​​to numbers from 0 to 9. The way I'm doing it now is just if((e.KeyChar < 48 || (e.KeyChar > 57)))

It seems a little cheap to just enter the values ​​for 0 and 9, and I would like to know how to get the value of the character, not its key.

EDIT: Thanks for the input; therefore there is generally no way to go from the value of e.KeyChar to the value of the input itself.

I would really like to accept my event, and access the character pressed directly, and not use e.KeyChar to get a numerical representation of this value.

+4
source share
3 answers

Here is an easier way to determine if the key pressed is a number or not:

 if (char.IsDigit(e.KeyChar)) { // doSomething(); } 
+5
source

KeyChar is a char value - the character itself - 48 and 57 - is ascii for 0 and 9 .

In C #, you can refer to a character through its numeric ASCII code or the actual character in single quotes. Therefore, your code may become:

 if((e.KeyChar < '0' || (e.KeyChar > '9'))) 

which is exactly the same.

+2
source

e.KeyChar corresponds to the char corresponding to the key pressed, not to the position .. The .NET Framework uses char to represent the Unicode character. If by "actual value of a character" you mean the integral value of characters 0-9, and not their Unicode values ​​(48-57), you can do this:

 var value = Char.GetNumericValue(e.KeyChar); 

To limit key values, press numbers between 0-9:

 if (!Char.IsDigit(e.KeyChar)) { e.Handled = true; return; } 

For a more complete solution that allows corrections:

 const char Backspace = '\u0008'; const char Delete = '\u007f'; if (!Char.IsDigit(e.KeyChar) // Allow 0-9 && e.KeyChar != Backspace // Allow backspace key && e.KeyChar != Delete) // Allow delete key { e.Handled = true; return; } 
+2
source

All Articles