Omniabsence
Omniabsence

Reputation: 171

Getting number as Int from a key press

I'm trying to get an integer from the number keys on the keyboard. For example, I want to press 5 and get the int 5.

I am using the KeyDown event and have the following:

    private void listBox1_KeyDown(object sender, KeyEventArgs e)
    {
            int rating = (int)e.KeyValue;
    }

And the output that I am getting are integers from the 50-60 range. I have tried also using e.KeyData and e.KeyCode without any luck.

Any help with this would be appreciated, I get the feeling it's something simple that I am overlooking or not understanding.

Upvotes: 1

Views: 7585

Answers (2)

Paul Mason
Paul Mason

Reputation: 1129

e.KeyValue returns the character code of the key pressed.

To get the actual digit you could do some character subtractions i.e.

int value = 0;
if (e.KeyValue >= 48 && e.KeyValue <= 57)
   value = e.KeyValue - 48;

NB: If you're wondering where 48 and 57 come from then you may want to check out the ASCII table: http://www.asciitable.com/index/asciifull.gif

Upvotes: 3

Matt
Matt

Reputation: 3680

This works.... kinda hacky...

Convert.ToInt32(e.KeyData.ToString()).Replace("D",""));

Upvotes: 1

Related Questions