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; 

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

Scenario – lookup a form by name and show it

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

Scenario – loop through all forms and close them

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

Note: Why not call form.Close() in the foreach loop? You can’t, because form.Close() changes the Application.OpenForms enumeration while you’re looping, which is not allowed in .NET. You’d get the following 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");
}

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.

Leave a Comment