简体   繁体   English

关闭C#.net中的MDI子窗体和父窗体的所有实例?

[英]Closing all the instances of MDI child forms and the parent form in C#.net?

IDE: Microsoft Visual Studio 2010 Platform : C#.net IDE:Microsoft Visual Studio 2010平台:C#.net

I have Child forms being loaded on the MDI parent form. 我在MDI父表单上加载了子表单。 So, now i want to close the MDI parent and all its child form when I click on the finish button which is in the last child form. 因此,现在我想在单击最后一个子窗体中的完成按钮时关闭MDI父窗体及其所有子窗体。 And once i click on the finish button it should close all the instances of parent and child form and open another form which is not part of the MDI parent form ? 一旦我单击完成按钮,它应该关闭所有父级和子级表单实例,并打开另一个不属于MDI父级表单的表单?

You could try to enumerate forms in Application.OpenForms , check their relations and close what you need: 您可以尝试在Application.OpenForms枚举表单,检查它们之间的关系并关闭所需的内容:

// close childs of parentForm
foreach(var form in Application.OpenForms)
    if(form.MDIParent == parentForm)
        form.Close();

Or you can register childs when they are created, so you will have a list of childs to close (pseudo-code): 或者,您可以在创建子项时对其进行注册 ,因此您将有一个要关闭的子项列表(伪代码):

// container for childs
List<Form> _childs = new List<Form>();
// when adding new form
Form1 form1 = new Form1();
form1.MDIParent = parentForm;
// register it
_childs.Add(form1);
// unregister when child is closed
form.OnClosed += ChildClosed;

// in ChildClosed
// unregiser
_childs.Remove(sender as Form);

It's just a robust idea. 这只是一个可靠的想法。 Childs registering could be optimized (by having base class for childs which does all that automatically). 可以优化孩子的注册(通过为孩子创建基类来自动完成所有工作)。 Registering childs is better if you going to have some extra data for each childs, to example, store they location and size for layouting. 如果您要为每个孩子提供一些额外的数据,例如为孩子存储位置和大小以进行布局,则注册孩子更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM