循环遍历所有 MDI 子级并关闭除当前窗体之外的所有其他窗体 [英] Loop through all MDI children and close all other forms except the current
问题描述
我正在使用 c# 开发一个 winforms 应用程序.我有一个 MDI 容器,它的左侧有一个菜单,按一下按钮就可以看到相应的表单.如果我单击打开 Form1 的按钮 3 次,则会打开该表单的 6 个实例.因此,我认为我必须编写一个方法来处理任何其他 Form1 实例.使用以下方法,我循环遍历 MDI 子项,但我需要一些帮助,如何关闭除新实例之外的所有其他实例.
I am working on a winforms application using c#. I have an MDI container that 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 children, but I want some help how to close all other instances except the new one.
public void DisposeAllButThis(Form form)
{
foreach (Form frm in this.MdiChildren)
{
if (frm == form)
{
frm.Dispose();
return;
}
}
}
推荐答案
你也需要检查表单是否是同类型的:
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();
}
}
}
有关关闭和处理的更多信息,请参阅:C# Form.Close vs Form.处置
For more information on Close and Dispose see: C# Form.Close vs Form.Dispose
这篇关于循环遍历所有 MDI 子级并关闭除当前窗体之外的所有其他窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!