How do I convert e.KeyChar to an actual character value when handling keyboard events?

21,496

Solution 1

Here is a simpler way of detecting if the key pressed is a digit or not:

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

Solution 2

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

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

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

which is exactly the same thing.

Solution 3

e.KeyChar is the char corresponding to the key pressed, not the position. The .NET Framework uses char to represent a Unicode character. If by "actual character value", 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 the values of the key press to digits 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;
}
Share:
21,496
user1993843
Author by

user1993843

Updated on April 18, 2020

Comments

  • user1993843
    user1993843 about 4 years

    All I'm wanting to do is get the actual character that is pressed whenever they key is entered for the event.

    The only option I'm seeing is e.KeyCharwhich will give me the position rather than the character itself.

    What I'm wanting to do is limit the values of the key press to digits between 0-9. The way I'm doing it right now is just if((e.KeyChar < 48 || (e.KeyChar > 57)))

    This seems a bit cheap to just put in the values for 0 and 9, and I'd love to know how to get the character value itself rather than its key.

    EDIT: Thanks for the input; so in general is there no way to go from having the e.KeyCharvalue to the value of the input itself.

    I'd really like to take my event, e, and access the character pressed directly as opposed to using e.KeyChar to get a numeric representation of that value.

  • Blorgbeard
    Blorgbeard about 11 years
    Keys values are keyboard scan-codes, you can't (meaningfully) cast them to char values.
  • 2Toad
    2Toad about 11 years
    @Blorgbeard thanks for pointing this out. Keys.Back worked, because Keys.Back = 8 and Backspace unicode = U+0008 (8). However, Keys.Delete = 46 and Delete unicode = U+007F (127), so it was erroneous. I've updated my answer to correct this.