C# 如何处理UWP中的硬件按钮。反压?
我有UWP应用程序与棱镜和AppShell。 我希望在通过BackButton退出之前添加确认对话框。 我试过这个:C# 如何处理UWP中的硬件按钮。反压?,c#,xaml,win-universal-app,prism,C#,Xaml,Win Universal App,Prism,我有UWP应用程序与棱镜和AppShell。 我希望在通过BackButton退出之前添加确认对话框。 我试过这个: protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args) { ... SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;
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;
}
}
我也试过了
HardwareButtons.BackPressed += App_BackRequested;
这也没有帮助。在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();
}
}
}
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
在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();
}
}
}
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
尝试将以下几行添加到
OnLaunchApplicationAsync
方法中
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();
}
};
//......
}
它适用于新的空白项目,但不适用于我的应用程序。rootFrame始终为空,如果我在弹出窗口中按“否”,应用程序仍将关闭。我这样认为是因为我有这样一个:protectedoverride UIElement CreateShell(Frame-rootFrame){var-shell=Container.Resolve();shell.SetContentFrame(rootFrame);return-shell;}+1。如果您解释了您通过此实现的功能,PO将更容易理解您如何解决问题。使用Prism可以处理硬件按钮事件,如(CameraButtonReleased、CameraButtonPressed、CameraButtonHalfPressed、GoBackRequested等),只需在OnLaunchApplication异步方法中实现即可