serhio
serhio

Reputation: 28586

Stop propagating keyboard event to the parent Form

I have a special TextBox that should be validated on Enter.

On this validation, the Form should net be however submitted if it has defined an AcceptButton.

In the following code I have 2 textBoxes: one normal, and one other - myTextBox - that validates itself on Enter (DoubleClick the form time to see it):

public partial class Form1 : Form
{
    private TextBox TextBox1;
    private MyTextBox MyTextBox1;
    private Button OKButton;
    public Form1()
    {
        InitializeComponent();

        TextBox1 = new TextBox();
        TextBox1.Parent = this;
        TextBox1.Location = new Point(0, 50);

        MyTextBox1 = new MyTextBox();
        MyTextBox1.Parent = this;
        MyTextBox1.Location = new Point(0, 100);
        MyTextBox1.Visible = false;

        OKButton = new Button();
        OKButton.Parent = this;
        OKButton.Location = new Point(0, 125);
        OKButton.Click += new EventHandler(OKButton_Click);

        this.AcceptButton = OKButton;
    }

    void OKButton_Click(object sender, EventArgs e)
    {
        if (MyTextBox1.Visible)
            return;
        Console.WriteLine("!!! OKButton_Click !!!");
    }

    protected override void OnMouseDoubleClick(MouseEventArgs e)
    {
        MyTextBox1.Visible = true;
        base.OnMouseDoubleClick(e);
    }
}

public class MyTextBox : TextBox
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            Console.WriteLine("!!! MyTextBox_Validation !!!");
            this.Visible = false;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

The fact of "Validated" is reflected by the myTextBox visibility, however this does not help, because in the OKBUtton_Click myTextBox1 is already made invisible...

enter image description here

Ideally, after myTextBox validation I would like to stop the Enter key Message propagation on the parent Form. Is it possible? If not, how should I validate MyTextBox without validating the form?

Upvotes: 0

Views: 1095

Answers (1)

tsiorn
tsiorn

Reputation: 2236

I hope I understand your question correctly. Did you try returning TRUE in your ProcessCmdKey override if you process the event? Returning true tells the event system that event was consumed and prevents further processing For example:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { 
    if (keyData == Keys.Enter) {
        Console.WriteLine("!!! MyTextBox_Validation !!!"); 
        this.Visible = false;
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData); 
}

Upvotes: 3

Related Questions