taji01 taji01 - 25 days ago 5
C# Question

Get the first index of form list and then close forms

I'm using

WinForms
. I want to close all of the forms except my main form called
Form1
. I noticed that my main Form is index 0, so i was wondering if i could do something like, close all the forms except of index 0. How can i do this? This is what i have so far.

List<Form> openForms = new List<Form>();

foreach (Form f in Application.OpenForms)
{
openForms.Add(f);
int mainFormIndex = openForms.IndexOf(0);
Console.WriteLine(": " + mainFormIndex);


if(mainFormIndex != 0)
{
this.Owner.Close();
}
else
{
this.Close();
}
}
}

Answer

You can check the name of Form and then close, for example if you need to keep Form1 open and close all other forms;

for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
{
    if (Application.OpenForms[i].Name != "Form1")
    {
        Application.OpenForms[i].Close();
    }
}