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

[startup form]

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;

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;

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.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in forms, user interface and tagged , , , , , , , , . Bookmark the permalink.