-1

I am trying to close a form if it is already opened, this form is the main of the application, so if I close all the instances of this form, the application ends. I am trying to look for if that form is opened, and I find it, close it if it is more than one opened:

With this I get the instances opened with the name "Main":

int nPrincOpen = openForms
 .OfType<Form>()
 .Where(form => String.Equals(form.Name, "Main"))
 .ToList()
 .Count();

And with this I close these forms, but I close all the forms:

for (int i = 0; i < nPrincOpen - 1; i++)
{
         Application.OpenForms
    .OfType<Form>()
    .Where(form => String.Equals(form.Name, "Main"))
    .ToList()
    .ForEach(form => form.Close());           
}

How could I close all the forms except one using link?

Gone But
  • 1
  • 1
  • is there a particular one you want to keep open or just any one of them.. if its just anyone, change you for loop to stop before you remove the last one `i < nPrincOpen - 2` – Dave Aug 10 '20 at 11:56
  • @Dave ok but the problems comes using link because I am closing all the forms called Main. So how can I close all the forms with this name except 1? – Gone But Aug 10 '20 at 12:00
  • Add .Take(Application.OpenForms.OfType
    ().Where(form => String.Equals(form.Name, "Main")).Count-1) before.ToList()
    – Silny ToJa Aug 10 '20 at 12:04
  • https://stackoverflow.com/a/10769349/17034 – Hans Passant Aug 10 '20 at 12:58

1 Answers1

1

Leave the first form open.

Application.OpenForms
.OfType<Form>()
.Where(form => String.Equals(form.Name, "Main"))
.Skip(1)
.ToList()
.ForEach(form => form.Close());  
Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32