WinForms: How to check if another form is open

If you’re working on a Windows Forms project and need to know which forms are open, use:

FormCollection forms = Application.OpenForms; 
Code language: C# (cs)

This gives you an IEnumerable collection of form objects that are currently open. You can lookup a form by name, by type, or loop through the list.

Example scenarios

There are many scenarios where you’d want to know which forms are open.

For example, you may want to know how many forms are currently open, or you want to see if a form is already open. Here are a few example scenarios to give you an idea about what you can do with Application.OpenForms.

Scenario – lookup a form by type and show it

var form = Application.OpenForms.OfType<frmQuery>().FirstOrDefault();
if(form == null)
{
	form = new frmQuery();
}
form.Show();
Code language: C# (cs)

Scenario – lookup a form by name and show it

var form = Application.OpenForms["frmQuery"];
if(form == null)
{
	form = new frmQuery();
}
form.Show();
Code language: C# (cs)

Scenario – loop through all forms and close them

Here’s an example of closing all open forms (except for the current form that is calling this code):

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());
}
Code language: C# (cs)

Don’t call form.Close() in the foreach loop. This changes the Application.OpenForms enumeration while you’re looping and results in an exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

Scenario – check if any forms are open

if(Application.OpenForms.Count > 1)
{
	MessageBox.Show("There are other forms open");
}
Code language: C# (cs)

Note: Why not check if the count > 0? Presumably we are calling this from a form that is currently open, therefore we know the count is at least 1, hence why we need to check count > 1.

Comments are closed.