How to make TextBox to receive only number key values using KeyDown Event in C#?

前端 未结 4 1563
攒了一身酷
攒了一身酷 2021-01-15 19:33

This code in my form updates the textBox1.Text twice whenever number keys are pressed.

private void textBox1_KeyDown( object sender, KeyEventArgs e )          


        
4条回答
  •  借酒劲吻你
    2021-01-15 19:56

    You can try like this:

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
       e.SuppressKeyPress = !(e.KeyValue >= 48 && e.KeyValue <= 57);
    }
    

    Check New keyboard APIs: KeyEventArgs.SuppressKeyPress

    The problem is that "Handled" doesn't take care of pending WM_CHAR messages already built up in the message queue - so setting Handled = true does not prevent a KeyPress from occurring.

    In order not to break anyone who has currently got e.Handled = true, we needed to add a new property called SuppressKeyChar. If we went the other way, if "handling" a keydown suddenly started to actually work, we might break folks who accidentally had this set to true.

提交回复
热议问题