Pregunta

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

¿Fue útil?

Solución

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

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

Otros consejos

I have suffered the same problem.

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

In this case you get key scan codes which also includes the 'movement' keys. I found out that if you use the normal KeyPress function and you set instead of:

e.Handled = true

then

e.KeyChar = (char) 0x00;

Now you get your requested function and I got mine

Example: (Hex input with separation):

// mtxtBoxKey.Mask = @"CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC";

    private void mtxtBoxKey_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar >= 'a' && e.KeyChar <= 'f')
            e.KeyChar = (char)(e.KeyChar - ' ');
        if (!((e.KeyChar == 0x08) || (e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar >= 'A' && e.KeyChar <= 'F')))
            e.KeyChar = (char) 0x00;
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top