'Strange: WinForms form closes automatically after button press

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());
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source