Closing secondary windows when main window is closed in UWP

In UWP it is not possible to show multiple windows for a single app. Depending on the usage, the user might expect secondary windows to close once the main window closes.

There are two problems to solve to make this happen:

  1. Figure out when the main window has been closed
  2. Close all secondary windows once the main window is closed

Both turned out to be harder than expected.

For the first issue, one might expect Window.Current.Closed or  Window.Current.CoreWindow.Closed to be signalled when the window is closed. This is not the case when a secondary window is open. After trying several other events, the ApplicationView.Consolidated event was the only one that I had success with. It would appear that when multiple windows are opened, the main window is not actually closed, but just hidden.

For the second issue, I likewise tried calling several Close methods to get the second window to close. I initially stayed away from Application.Current.Exit because the documentation says it should not be called, but the MSDN article for multiple views in UWP actually recommends invoking it to close down the main window and thereby all secondary windows as well.

So the final solution ended up being:

ApplicationView.GetForCurrentView().Consolidated += (ss, ee) =>
     (ss, ee) => {Application.Current.Exit();};