how to supress backspace and delete keys


  • i have a masked text box control that is set for overwrite.  i want to disable backspace and delete keys.  to that end i added the following code to my form...

            private void maskedTextBoxTime_KeyDown(object sender, KeyEventArgs e)
                if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete)
                    e.SuppressKeyPress = true;

    however, when i run the application and set focus to the masked text box control, backspace and delete continue to function.  what am i doing wrong here?


    Friday, January 16, 2009 4:26 AM

All replies

  • Historically MaskedTextBox has always bugs and issues related to it.
    I did some test with your code and in effect DO NOT WORK, only if you eliminate the mask which has no point.
    What i recomment use an alternative to enter the data. For time use DateTimePicker and set Format property to Time.
    Friday, January 16, 2009 3:07 PM
  • That's strange, I have no problems with this.  Are you sure you hooked up your event handler to the control? Post the portion of your designer code that declares the MaskedTextBox.
    David Morton -
    Friday, January 16, 2009 3:19 PM
  • well, it is not my issue but I did reproduce it. I think you only have to draw the MaskedTextBox in a form, declare a mask and the KeyDown event.

    hre is what you ask for:


    // maskedTextBox1


    this.maskedTextBox1.Location = new System.Drawing.Point(320, 372);

    this.maskedTextBox1.Mask = "90:00";

    this.maskedTextBox1.Name = "maskedTextBox1";

    this.maskedTextBox1.Size = new System.Drawing.Size(94, 20);

    this.maskedTextBox1.TabIndex = 5;

    this.maskedTextBox1.ValidatingType = typeof(System.DateTime);

    this.maskedTextBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.maskedTextBox1_KeyDown);

    Friday, January 16, 2009 5:56 PM