Understand the startup form (or main form) in C#

When a C# Windows Forms program starts, it displays a startup form. That form has a special place in the program's life cycle. If that form ever closes, the application ends.

The program can create and close as many other forms as it wants in any order without closing the program. The startup form is special in that respect.

When you click this example's New Form button, the following code displays a new instance of the main form.

// Display a new form with a blue background.
private void btnNewForm_Click(object sender, EventArgs e)
{
    Form1 frm = new Form1();
    frm.BackColor = Color.LightBlue;
    frm.Show();
}

This code simply creates a new instance of the form, sets its background color to light blue so you can distinguish the new forms from the startup form, and displays the form.

Run the program and create and close a few forms. Then create a form or two and close the startup form to see that the whole program stops.

This is not really much of a problem as long as you are aware of the situation.

So what can you do if you don't want the user to stop the application by closing the main form? This example uses the following FormClosing event handler to prevent the startup form from closing if any form's "Prevent Startup From Closing" CheckBox is checked.

// If this is the main form and any other forms have their
// Prevent Startup From Closing boxes checked, don't close.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // See if this is the main form.
    if (this == Application.OpenForms[0])
        // See if any form has the CheckBox checked.
        foreach (Form1 frm in Application.OpenForms)
            if (frm.chkPreventStartupFromClosing.Checked)
            {
                e.Cancel = true;
                break;
            }
}

If the form that is executing the FormClosing event handler is the startup form, then it is first in the Application object's OpenForms collection. If this is the startup form, then the code loops through all of the open forms. If the CheckBox on any open form is checked, then the event handler sets e.Cancel to true to prevent the form from closing.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.