C# WinForm和WPF关闭所有子窗口的方法

WinForm中操作:

// 遍历并关闭所有子窗口
FormCollection childCollection = Application.OpenForms;
for (int i = childCollection.Count; i-- > 0;)
{
    if (childCollection[i].Name != "父窗口标题") 
childCollection[i].Close(); }
// 或者也可以这样写: FormCollection childCollection = Application.OpenForms; for (int i = childCollection.Count; i-- > 0;) { if (childCollection[i].Name != this.Text)
childCollection[i].Close(); }

 

WPF中操作:

// 遍历并关闭所有子窗口
Window[] childArray = Application.Current.Windows.Cast<Window>().ToArray();
for (int i = childArray.Length; i-- > 0;)
{
    Window item = childArray[i];
    if (item.Title == "") continue; // 忽略无标题窗口
    if (item.Title != "父窗口标题") 
item.Close(); }
// 或者也可以这样写: Window[] childArray = Application.Current.Windows.Cast<Window>().ToArray(); for (int i = childArray.Length; i-- > 0;) { Window item = childArray[i]; if (item.Title == "")
continue; // 忽略无标题窗口 if (item.Title != this.Title)
item.Close(); }

 

总结, 注意WPF中调试要排除无标题窗口,否则会导致程序被关闭。
这里的无标题窗口是WPF的界面调试器,如果它被关闭会导致被调试的程序也被关闭,Release程序可以不用对无标题窗口进行排除。

 

原文链接:https://blog.csdn.net/ymh441915964/article/details/78997725

posted @ 2024-05-21 16:01  龙骑科技  阅读(28)  评论(0编辑  收藏  举报