KeyDown event - how to easily know if the key pressed is numeric?

青春壹個敷衍的年華 提交于 2019-11-29 10:00:24

If you use the KeyPress event, the event signature has a KeyPressEventArgs with a KeyChar member that gives you the character for the numberpad keys. You can do a TryParse on that to figure out if its a number or not.

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    int i;
    if (int.TryParse(e.KeyChar.ToString(), out i))
    {
        MessageBox.Show("Number");
    }
}

Try

if ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
    (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
    e.KeyCode == Keys.Decimal)
{
    // Edit mode
}

Why use keycodes, when you can use this:

void Control_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (Char.IsDigit(e.KeyChar))
        {
            //do something
        }
        else
        {
            //do something else
        }
    }

It's cleaner and even if microsoft decides to change all enums vlue, it still would work

Sorcerer86pt's solution was the simplest, however, when a user presses a control key, like backspace, then it breaks. To solve that problem, you can use the following snippet:

void KeyPress(object sender, KeyPressEventArgs e)
{    
    if(!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))
    {
        //The char is not a number or a control key
        //Handle the event so the key press is accepted
        e.Handled = true;
        //Get out of there - make it safe to add stuff after the if statement
        return;
    }
    //e.Handled remains false so the keypress is not accepted
}

If you're using WPF, you might find that a TextBox doesn't have a KeyPressed event. To fix this, I used the following code.

void ValidateKeyPress(object sender, KeyEventArgs e)
{
    char keyPressed = WPFUtils.Interop.Keyboard.GetCharFromKey(e.Key);
    if (!Char.IsNumber(keyPressed) && !Char.IsControl(keyPressed))
    {
        //As above
        e.Handled = true;
        return;
    }
}

You may notice the weird function call WPFUtils.Interop.Keyboard.GetCharFromKey(e.Key) this is one of the useful functions I've collected. You can find it here.

nick

Just get the last char from the Key that will be number if a number was pressed. This method works with KeyDown events not needing any other conditions.

Just call this static method and pass in the Key to check

public static bool IsNumber(Keys key)
{
  string num = key.ToString().Substring(key.ToString().Length - 1);
  Int64 i64;
  if (Int64.TryParse(num, out i64))
  {
    return true;               
  }
  return false;
}

On the msdn help page they use this code in their example:

// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)

...

// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)

A bit more condensed version:

    private void KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !Char.IsDigit(e.KeyChar); // only allow a user to enter numbers
    }
MrFox
void dataGridView1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Used this to find they key values.
    //label1.Text += e.KeyValue;

    // Check if key is numeric value.
    if((e.KeyValue >= 48 && e.KeyValue <= 57) || (e.KeyValue >= 97 && e.KeyValue <= 105))
        System.Console.WriteLine("Pressed key is numeric");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!