1

在我的 UWP 应用程序中,当我单击移动后退按钮应用程序关闭时,请将此代码添加到 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! \nOr Press Refresh Button to Go Back");
               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();
               }
           }
       }

    public App()
    {            
        this.InitializeComponent();
        this.Suspending += OnSuspending;

    /*  Because of this line my app work on mobile great but when
        when i debug on pc it through exception "show in image" */
        HardwareButtons.BackPressed += HardwareButtons_BackPressed;
    }

当我在手机上调试应用程序时完成所有这些代码后,应用程序成功运行 - 移动调试:

在此处输入图像描述

但是当使用相同的代码在 pc 中调试时,它会显示此错误 - PC 调试:

在此处输入图像描述

当我删除HardwareButtons.BackPressed += HardwareButtons_BackPressed;然后解决了 pc 调试问题但在移动调试中返回按钮再次不起作用。

4

1 回答 1

1

原因是HardwareButtonsAPI 不是处理后退按钮的通用解决方案。此 API 仅在移动扩展 SDK 中可用,尝试在其他 SKU 上调用它会导致此异常,因为该类型不可用。

要在所有系统上启用相同的功能,您需要使用新的通用后退按钮事件:

SystemNavigationManager.GetForCurrentView().BackRequested += BackButtonHandler;

这同样适用于手机、PC、平板电脑、Xbox One、Surface Hub 和 HoloLens。

在 PC 上,默认情况下不显示此按钮,因此您必须手动显示或创建自己的按钮。要在窗口的标题栏中显示 Back 按钮,请使用:

SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
   AppViewBackButtonVisibility.Visible;

建议您隐藏此按钮一次Frame.CanGoBack为假,因为在这种情况下该按钮不再有用。您应该在框架的每次导航之后执行此操作。最好的地方是在设置根框架时App.xaml.cs

 Frame rootFrame = Window.Current.Content as Frame;
 rootFrame.Navigated += UpdateAppViewBackButton;

现在处理程序可能如下所示:

private void UpdateAppViewBackButton( object sender, NavigationEventArgs e )
{
    Frame frame = (Frame) sender;
    var systemNavigationManager = SystemNavigationManager.GetForCurrentView();
    systemNavigationManager.AppViewBackButtonVisibility =
        frame.CanGoBack ? AppViewBackButtonVisibility.Visible : 
                          AppViewBackButtonVisibility.Collapsed;
}

在应用程序关闭

我还注意到您正在使用Application.Current.Exit();退出应用程序。但是,不建议这样做。一旦用户在对话框中选择确定,您应该设置e.Handled = false并让系统手动处理应用程序关闭。这将确保应用程序暂停将按预期运行,并且如果系统有足够的资源,应用程序将保留在内存中,然后将再次更快地启动。Application.Current.Exit()杀死应用程序,不推荐用于 UWP 应用程序。

要记住的一件事是,在桌面上,目前无法捕捉用户单击应用程序标题栏中的关闭按钮,因此很遗憾在这种情况下不会显示您的确认对话框。

于 2016-09-01T06:28:55.630 回答