How to check if another form is open

By FoxLearn 1/21/2025 4:38:48 AM   229
When developing a Windows Forms application in C#, you might need to check whether a form is already open.

This is often useful in scenarios where you want to prevent duplicate forms from appearing or handle the state of multiple open forms.

In a Windows Forms application, the Application.OpenForms property returns a collection of all currently open forms. It is of type FormCollection, which implements IEnumerable. You can loop through this collection to identify and interact with the open forms. You can also search for a specific form by its type or name.

Lookup a Form by Type and Show It

You may want to check if a form of a specific type is already open, and if not, create and display it.

var form = Application.OpenForms.OfType<frmAbout>().FirstOrDefault();
if (form == null)
{
    form = new frmAbout();
}
form.Show();

In this example, the code searches for an open form of type frmAbout. If no such form is found, a new instance of frmAbout is created and shown.

Lookup a Form by Name and Show It

Alternatively, you can search for an open form by its name (which is the Name property of the form).

var form = Application.OpenForms["frmAbout"];
if (form == null)
{
    form = new frmQuery();
}
form.Show();

If the form is not open, the code creates and displays a new instance of the form.

Loop Through All Forms and Close Them

If you need to close all open forms except the current one, you can loop through the Application.OpenForms collection and close each form. However, it’s important to avoid modifying the collection during iteration, as this can result in a System.InvalidOperationException.

private void CloseAllOtherForms()
{
    List<Form> formsToClose = new List<Form>();
    foreach (Form form in Application.OpenForms)
    {
        if (form != this)
        {
            formsToClose.Add(form);
        }
    }

    formsToClose.ForEach(f => f.Close());
}

This code first creates a list of forms to be closed and then closes each form after the loop completes, avoiding modification of the collection while iterating.

Check if Any Forms Are Open

Sometimes, you may just want to check whether any other forms are open in addition to the current form.

if (Application.OpenForms.Count > 1)
{
    MessageBox.Show("There are other forms open");
}

Note that the count is checked to be greater than 1. This is because when the code is called from an already open form, the count will always be at least 1 (the current form). Thus, checking if the count is greater than 1 ensures there are additional forms open.

The Application.OpenForms property is a powerful tool for managing forms in a Windows Forms application. It allows you to check which forms are open, search for forms by type or name, and even close forms programmatically.