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();};

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s