Reputation: 2615
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();
}
}
}
Upvotes: 2
Views: 3271
Reputation: 125187
You can close all forms except Form1
instance using linq this way:
Application.OpenForms.Cast<Form>().Where(x => !(x is Form1))
.ToList().ForEach(x => x.Close());
Upvotes: 3
Reputation: 63065
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();
}
}
Upvotes: 1