Search code examples
c#winformsmaskedtextbox

Maskedtextbox ignores e.Handled = true /How to prevent input


I have a masked textbox (Note: NO normal Texbox, i searched the web and found only articles which are related to a normal textbox):

        this.maskedTextBox1 = new System.Windows.Forms.MaskedTextBox();
        this.maskedTextBox1.Location = new System.Drawing.Point(12, 30);
        this.maskedTextBox1.Mask = "??????????????????????????";   //Just as example
        this.maskedTextBox1.Name = "maskedTextBox1";
        this.maskedTextBox1.Size = new System.Drawing.Size(260, 20);
        this.maskedTextBox1.TabIndex = 0;
        this.maskedTextBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.maskedTextBox1_KeyPress);

I want to prevent input to i casue i want to handle the input myself. The problem is, that this seems to be not possible. I tried to set e.Handled to true, but it totally ignores it.

private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = true;
    }

Is there a way to prevent input into a masked texbox? Also does anyone know why setting e.Handled = trues has no effect?

Many thanks in advance


Solution

  • You can try the KeyDown event instead and set SuppressKeyPress = true;:

    private void maskedTextBox1_KeyDown(object sender, KeyEventArgs e){    
       e.SuppressKeyPress = true;
    }