Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange: WinForms form closes automatically after button press

Tags:

c#

.net

winforms

My app is WinForms .NET 4 (C#) and one of the forms keeps on closing automatically after pressing a button.

  • The form DOES have default Accept and Cancel buttons but these are not touched.
  • There is a ButtonTestConnection_Click event which when clicked, does its job but closes the form somehow.
  • I am using the mouse to click the button so this is NOT a case of cascading keystrokes.
  • I am NOT setting the DialogResult in this function.

I also tried to check for stray this.Close / this.Dispose calls but found none.

Here is the code:

private void ButtonTestConnection_Click (object sender, System.EventArgs e)
{
    this.Enabled = false;
    this.Cursor = System.Windows.Forms.Cursors.WaitCursor;

    this.ProgressBar.Minimum = 0;
    this.ProgressBar.Maximum = 500;
    this.ProgressBar.Value = 0;

    this.ProgressBar.Visible = true;
    this.ButtonTestConnection.Visible = false;

    try
    {
        while (this.ProgressBar.Value < this.ProgressBar.Maximum)
        {
            // Some proxy code.
            this.ProgressBar.Value++;
        }
    }
    catch
    {
    }

    this.ProgressBar.Visible = false;
    this.ButtonTestConnection.Visible = true;

    this.ProgressBar.Invalidate();
    System.Windows.Forms.Application.DoEvents();
    System.Threading.Thread.Sleep(10);

    this.Cursor = System.Windows.Forms.Cursors.Default;
    this.Enabled = true;

    System.Windows.Forms.MessageBox.Show(result.ToString());
}
like image 561
Raheel Khan Avatar asked Jun 05 '12 15:06

Raheel Khan


1 Answers

Check if the property DialogResult on the button equals to None.
If not, then the form will be closed when you hit that button and the form will return the setting of the Button's DialogResult property.

Usually, this happens a lot when you copy/paste an existing form's button but forget to remove on the pasted button the original DialogResult setting

like image 105
Steve Avatar answered Sep 20 '22 13:09

Steve