如何在用户点击右上角X关闭UWP应用时显示消息对话框
UWP点击关闭按钮弹出确认对话框的实现方法
要实现点击UWP应用右上角关闭按钮时弹出确认对话框,核心是监听窗口的Closing事件,在事件中拦截默认关闭行为,根据用户选择决定是否关闭应用。
实现步骤
注册窗口关闭事件
在应用启动后(比如App.xaml.cs的OnLaunched方法,或者主页面的Loaded事件中),获取当前窗口并注册Closing事件:protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { rootFrame.Navigate(typeof(MainPage), e.Arguments); } Window.Current.Activate(); // 注册窗口关闭事件 Window.Current.Closing += CurrentWindow_Closing; } }编写事件处理逻辑
实现Closing事件的处理方法,拦截默认关闭行为,弹出对话框并根据用户选择执行对应操作:private async void CurrentWindow_Closing(object sender, WindowEventArgs e) { // 先取消默认的关闭操作 e.Cancel = true; // 创建确认对话框 var confirmDialog = new MessageDialog("确定要关闭应用吗?", "关闭提示"); // 添加确认按钮 confirmDialog.Commands.Add(new UICommand("确定", cmd => { // 用户确认关闭,退出应用 Application.Current.Exit(); })); // 添加取消按钮 confirmDialog.Commands.Add(new UICommand("取消", cmd => { // 用户取消,保持窗口打开 e.Cancel = true; })); // 设置默认选中命令和取消命令的索引 confirmDialog.DefaultCommandIndex = 0; confirmDialog.CancelCommandIndex = 1; // 显示对话框 await confirmDialog.ShowAsync(); }必要的命名空间引用
确保代码文件顶部引用了以下命名空间:using Windows.UI.Xaml; using Windows.UI.Popups; using Windows.UI.Xaml.Controls;
注意事项
- 若在页面中注册事件,需确保在页面卸载时取消注册,避免内存泄漏。
MessageDialog在UWP中属于系统弹窗,需保证应用有对应的权限(通常默认已具备)。- 如果需要在关闭前执行数据保存等操作,可以在用户点击“确定”后先完成异步操作,再调用
Application.Current.Exit()。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

