关闭除主表单以外的所有表单

时间:2016-11-12 08:49:41

标签: c# .net forms winforms list

我正在使用WinForms。我希望关闭除名为Form1的主要表单之外的所有表单。我注意到我的主要表单是索引0,所以我想知道我是否可以做类似的事情,关闭除索引0之外的所有表单。我怎么能这样做?这就是我到目前为止所做的。

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

2 个答案:

答案 0 :(得分:2)

您可以使用linq以这种方式关闭除/home/user/Android/nexus10/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7/bin/../lib/gcc/arm-linux-androideabi/4.7/../../../../arm-linux-androideabi/bin/ld: error: cannot open crtbegin_dynamic.o: No such file or directory /home/user/Android/nexus10/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7/bin/../lib/gcc/arm-linux-androideabi/4.7/../../../../arm-linux-androideabi/bin/ld: error: cannot open crtend_android.o: No such file or directory /home/user/Android/nexus10/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7/bin/../lib/gcc/arm-linux-androideabi/4.7/../../../../arm-linux-androideabi/bin/ld: error: cannot find -lstdc++ /home/user/Android/nexus10/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7/bin/../lib/gcc/arm-linux-androideabi/4.7/../../../../arm-linux-androideabi/bin/ld: error: cannot find -lm /home/user/Android/nexus10/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7/bin/../lib/gcc/arm-linux-androideabi/4.7/../../../../arm-linux-androideabi/bin/ld: error: cannot find -lc /home/user/Android/nexus10/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7/bin/../lib/gcc/arm-linux-androideabi/4.7/../../../../arm-linux-androideabi/bin/ld: error: cannot find -ldl collect2: error: ld returned 1 exit status 实例之外的所有表单:

Form1

答案 1 :(得分:1)

您可以检查表单的名称然后关闭,例如,如果您需要保持Form1打开并关闭所有其他表单;

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