Skip to content

Commit 202567c

Browse files
Copilotniels9001
andcommitted
Fix window lifecycle management to prevent exceptions when closing main window with child windows
Co-authored-by: niels9001 <9866362+niels9001@users.noreply.github.com>
1 parent d3aa725 commit 202567c

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

WinUIGallery/App.xaml.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using Microsoft.Windows.AppNotifications.Builder;
99
using Microsoft.Windows.BadgeNotifications;
1010
using System;
11+
using System.Collections.Generic;
1112
using System.Diagnostics;
1213
using System.Linq;
1314
using Windows.ApplicationModel.Activation;
@@ -60,6 +61,23 @@ protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs ar
6061
MainWindow.Closed += (s, e) =>
6162
{
6263
BadgeNotificationManager.Current.ClearBadge();
64+
65+
// Close all remaining active windows to prevent resource disposal conflicts
66+
var activeWindows = new List<Window>(WindowHelper.ActiveWindows);
67+
foreach (var window in activeWindows)
68+
{
69+
if (window != s) // Don't try to close the window that's already closing
70+
{
71+
try
72+
{
73+
window.Close();
74+
}
75+
catch
76+
{
77+
// Ignore any exceptions during cleanup
78+
}
79+
}
80+
}
6381
};
6482
}
6583

WinUIGallery/Samples/ControlPages/CreateMultipleWindowsPage.xaml.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using Microsoft.UI.Xaml;
55
using Microsoft.UI.Xaml.Controls;
6+
using WinUIGallery.Helpers;
67
using WinUIGallery.Pages;
78

89
namespace WinUIGallery.ControlPages;
@@ -17,6 +18,7 @@ public CreateMultipleWindowsPage()
1718
private void createNewWindow_Click(object sender, RoutedEventArgs e)
1819
{
1920
var newWindow = new MainWindow();
21+
WindowHelper.TrackWindow(newWindow);
2022
newWindow.Activate();
2123

2224
var targetPageType = typeof(HomePage);

0 commit comments

Comments
 (0)