Dmitry
Dmitry

Reputation: 1165

How to handled HardwareButtons.BackPressed in UWP?

I have UWP app with Prism and AppShell. I want add confirmation dialog before exit by BackButton. I tried this:

protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
    {
        ...
        SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;

        ...
    }

private void App_BackRequested(object sender, BackRequestedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        if (rootFrame == null)
        {  
           return;
        }

        if (rootFrame.CanGoBack && e.Handled == false)
        {
            <add confirm dialog here>
            e.Handled = true;
        }
    }

But rootFrame always is null and if history stack empty and I pressed BackButton app is close even if imake this:

private void App_BackRequested(object sender, BackRequestedEventArgs e)
{
        e.Handled = true;
}

Also I tried

HardwareButtons.BackPressed += App_BackRequested;

and it not help too.

Upvotes: 3

Views: 629

Answers (2)

Taha Azab
Taha Azab

Reputation: 34

try to add these below lines to OnLaunchApplicationAsync method

protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
    {
        //......
        DeviceGestureService.GoBackRequested += (s, e) =>
        {
            e.Handled = true;
            e.Cancel = true;
            if (NavigationService.CanGoBack())
            {
                NavigationService.GoBack();
            }
            else
            {
                // PUT YOUR LOGIC HERE (Confirmation dialog before exit)
                Application.Current.Exit();
            }
        };
        //......
     }

Upvotes: 0

artista_14
artista_14

Reputation: 716

Add code in App.xaml.cs -

 private async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
    {

        e.Handled = true;
        Frame rootFrame = Window.Current.Content as Frame;
        if (rootFrame.CanGoBack && rootFrame != null)
        {

            rootFrame.GoBack();
        }
        else
        {
            var msg = new MessageDialog("Confirm Close");
            var okBtn = new UICommand("OK");
            var cancelBtn = new UICommand("Cancel");
            msg.Commands.Add(okBtn);
            msg.Commands.Add(cancelBtn);
            IUICommand result = await msg.ShowAsync();

            if (result != null && result.Label == "OK")
            {
                Application.Current.Exit();
            }
        }
    }

Add this line in constructor of App.xaml.cs -

HardwareButtons.BackPressed += HardwareButtons_BackPressed;

Upvotes: 4

Related Questions