C# 循环遍历所有 MDI childer 并关闭除当前窗体之外的所有其他窗体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11308821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# loop through all MDI childer and close all other forms except the current
提问by user1292656
I am working on a winforms application using c#. I have an mdi container which has a menu on the left and by pushing a button then the appropriate form is visible. If i click for ex 3 times the button which opens Form1 the 6 instances of the form are opened. Thus i thought that i have to write a method that disposes any other Form1 instances. With the following method i m looping through the MDI childer but i want some help how to close all other instances except the new one.
我正在使用 c# 开发一个 winforms 应用程序。我有一个 mdi 容器,它的左侧有一个菜单,按一下按钮就可以看到相应的表单。如果我单击打开 Form1 的按钮 3 次,则会打开该表单的 6 个实例。因此,我认为我必须编写一个方法来处理任何其他 Form1 实例。使用以下方法循环遍历 MDI childer,但我需要一些帮助来关闭除新实例之外的所有其他实例。
public void DisposeAllButThis(Form form)
{
foreach (Form frm in this.MdiChildren)
{
if (frm == form)
{
frm.Dispose();
return;
}
}
}
采纳答案by Erno
You need to check whether the form is of the same type too:
您还需要检查表单是否属于同一类型:
public void DisposeAllButThis(Form form)
{
foreach (Form frm in this.MdiChildren)
{
if (frm.GetType() == form.GetType()
&& frm != form)
{
frm.Dispose();
frm.Close();
}
}
}
For more information on Close and Dispose see: C# Form.Close vs Form.Dispose
有关 Close 和 Dispose 的更多信息,请参阅:C# Form.Close 与 Form.Dispose
回答by Asif Mushtaq
foreach (Form frm in this.MdiChildren)
{
if (frm != form)
{
frm.Dispose();
return;
}
}
回答by Andriy Vandych
public void DisposeAllButThis(Form form)
{
foreach (Form frm in this.MdiChildren)
{
if (frm != form)
{
frm.Dispose();
frm.Close();
}
}
return;
}
回答by Reza Paidar
By this fanction You can call it from another class :
and note of this : frm.GetType() != Parent.GetType()
通过这个幻想你可以从另一个类调用它:并注意这一点: frm.GetType() != Parent.GetType()
public void DisposeAllButThis(Form parentForm)
{
foreach (Form frm in Parent.MdiChildren)
{
if (frm.GetType() != Parent.GetType()
&& frm != Parent)
{
frm.Close();
}
}
}
回答by Dara.Joukar
private void closallforms()
{
foreach (Form frm in this.MdiChildren)
{
if (frm != Parent)
{
frm.Close();
}
}
}
回答by Thanaphon SPK
if you call from another child form you can use: this.DisposeAllButThis(this.FindForm());
如果您从另一个子表单调用,您可以使用: this.DisposeAllButThis(this.FindForm());
and use the method:
并使用方法:
private void DisposeAllButThis(Form form)
{
foreach (Form frm in ParentForm.MdiChildren)
{
if (frm != form)
{
frm.Dispose();
frm.Close();
}
}
}

