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

后端 未结 8 1889
天命终不由人
天命终不由人 2020-12-19 03:00

I am currently handling the KeyDown event of a DataGridView control. One of the columns is filled by calculated values and I want the user to be able to override the cell va

8条回答
  •  情歌与酒
    2020-12-19 03:45

    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.

提交回复
热议问题