The KeyPress event of C# text box limits keyboard input

Transfer from: http://hi.baidu.com/6phone/item/ca770c0f7c4b8f70bfe97e02

Assuming that the text box only allows the input of numbers, decimal point and backspace and enter keys, then:

method one:

Code for text box 1 (KeyPress event of TextBox1): 

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {             //Prevent key input from the keyboard             e.Handled = true;

           //Do not block
            if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar =='. when entering numbers from 0-9, decimal point, carriage return and backspace keys . '|| e.KeyChar == 13 || e.KeyChar == (char)8)
            {                 e.Handled = false;             }          }



e.handled represents whether the button action is handled by the user. If it is true, it is handled by the user and the system no longer intervenes. The application here is interception, that is, to notify the system that I want to process this data, but I can’t leave it, then The data is discarded, thereby achieving the effect of interception. Method 2: Restrict only numbers, decimal point and carriage return

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

        {

            if (e.KeyChar < 48 || e.KeyChar > 57)

            {

                if (e.KeyChar != 8 && e.KeyChar != 13 && e.KeyChar != 46)

                {

                    MessageBox.Show("Warning: You must enter a number!");

                    txtPrice.Focus();

                    txtPrice.SelectAll();

                    e.KeyChar = '\0';

                }

            }

     }

Guess you like

Origin blog.csdn.net/youarenotme/article/details/72985680