C# UWP closing application multiple views

1.5k Views Asked by At

I have a UWP app that dynamically creates another view. But, the problem is when I close the first window, the second still stays on.

With this code I am creating new view:

        CoreApplicationView newView = CoreApplication.CreateNewView();
        int newViewId = 0;
        await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            Frame frame = new Frame();
            frame.Navigate(typeof(SecondPage), null);
            Window.Current.Content = frame;
            // You have to activate the window in order to show it later.
            Window.Current.Activate();

            newViewId = ApplicationView.GetForCurrentView().Id;
        });
        bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);

How to close the application when user close the first window?

1

There are 1 best solutions below

0
On

Please refer to Show multiple views for an app.

If secondary views are open, the main view’s window can be hidden – for example, by clicking the close (x) button in the window title bar - but its thread remains active. Calling Close on the main view’s Window causes an InvalidOperationException to occur. (Use Application.Exit to close your app.) If the main view’s thread is terminated, the app closes.

private void Btn_Click(object sender, RoutedEventArgs e)
{
    Application.Current.Exit();
}

You could also choose if you want to close the initial window and remove it from the taskbar by specifying the value of ApplicationViewSwitchingOptions.So that there is a single view on your desktop. You just need to close it for closing the application.

 private int currentViewId = ApplicationView.GetForCurrentView().Id;
 private async void ShowNewView()
 {
     CoreApplicationView newView = CoreApplication.CreateNewView();
     int newViewId = 0;
     await newView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     {
         Frame frame = new Frame();
         frame.Navigate(typeof(SecondPage), null);
         Window.Current.Content = frame;
         Window.Current.Activate();
         newViewId = ApplicationView.GetForCurrentView().Id;
     });

     await ApplicationViewSwitcher.SwitchAsync(newViewId, currentViewId, ApplicationViewSwitchingOptions.ConsolidateViews);
 }