Zereges Zereges - 2 months ago 22
C# Question

C# MessageBox casues key handler to ignore SurpressKeyPress

Consider Windows Forms application with following components

partial class Form1
{
private System.Windows.Forms.TextBox textBox = new System.Windows.Forms.TextBox();
private void InitializeComponent()
{
textBox.Multiline = true;

Controls.Add(this.textBox);
KeyPreview = true;
KeyDown += new System.Windows.Forms.KeyEventHandler(Form1_KeyDown);
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
if (textBox.Text.Length > 10)
MessageBox.Show("Test");
}
}
}


Now, expected behaviour, is to write text to
textBox
and press enter. If the text is


  • not long enough, nothing should happen (due to
    e.SuppressKeyPress = true;
    ) and that happens.

  • is long enough, empty
    MessageBox
    should pop up and
    Keys.Enter
    should not reach the
    textBox
    component. However, when MessageBox pops up, the text will contain line-break caused by the enter.



Is this intended behaviour, or bug, or am I the only on experiencing this?

Answer

You can solve the problem by calling the message box using BeginInvoke this way:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.SuppressKeyPress = true;
        this.BeginInvoke(new Action(() => {
            if (textBox.Text.Length > 10)
                MessageBox.Show("Test");
        }));
    }
}