You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET MAUI Windows应用关闭时弹出二次确认对话框?

.NET MAUI Windows应用:实现关闭窗口时的确认对话框

我用.NET MAUI开发Windows桌面应用,想要实现点击窗口右上角的“X”关闭按钮时,弹出确认对话框询问用户是否确定关闭应用。

之前尝试用MAUI的Window.Destroying事件处理,但这个事件只能触发关闭时的逻辑,无法阻止应用关闭;注册异步方法也没用,系统不会等待异步操作完成,直接就关闭了应用——比如下面的代码只会输出"Before await",对话框根本弹不出来:

protected override Window CreateWindow(IActivationState? activationState)
{
    var window = new Window(new AppShell())
    {
        MinimumHeight = 520,
        MinimumWidth = 850
    };

    window.Destroying += async (sender, args) =>
    {
        Debug.WriteLine("Before await");
        await Application.Current.MainPage.DisplayAlert("xx", "xxx", "y", "n");
        Debug.WriteLine("After await");
    };

    return window;
}

而且我只找到Android和macOS的相关解决方案,没有Windows的,这里提供针对Windows平台的解决方法:

解决方案:利用Windows原生窗口的Closing事件

MAUI的跨平台Destroying事件不支持拦截关闭操作,所以需要直接调用WinUI的原生API处理窗口的Closing事件,这个事件允许我们取消默认关闭行为,等待用户确认后再决定是否退出。

代码实现

在App.xaml.cs的CreateWindow方法中,针对Windows平台获取原生窗口实例,注册Closing事件:

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
    }

    protected override Window CreateWindow(IActivationState? activationState)
    {
        var window = new Window(new AppShell())
        {
            MinimumHeight = 520,
            MinimumWidth = 850
        };

#if WINDOWS
        // 等待窗口加载完成后获取原生窗口实例
        window.Loaded += (sender, args) =>
        {
            var nativeWinUIWindow = window.Handler.PlatformView as Microsoft.UI.Xaml.Window;
            if (nativeWinUIWindow != null)
            {
                nativeWinUIWindow.Closing += async (s, closingArgs) =>
                {
                    // 先取消默认的关闭行为
                    closingArgs.Cancel = true;

                    // 弹出确认对话框
                    bool confirmClose = await Application.Current.MainPage.DisplayAlert(
                        "确认关闭",
                        "你确定要退出应用吗?",
                        "确定",
                        "取消");

                    if (confirmClose)
                    {
                        // 用户确认关闭,主动退出应用
                        Application.Current.Quit();
                    }
                    // 用户取消则不做操作,窗口保持打开
                };
            }
        };
#endif

        return window;
    }
}

代码说明

  1. 平台限定:用#if WINDOWS包裹代码,确保只在Windows平台执行,不影响其他平台的编译和运行。
  2. 延迟获取原生窗口:窗口的Handler在创建初期可能未初始化完成,所以在Loaded事件中获取原生WinUI窗口实例更可靠。
  3. 拦截关闭行为:通过closingArgs.Cancel = true取消系统默认的关闭流程。
  4. 异步确认对话框:弹出MAUI的跨平台DisplayAlert,等待用户选择;如果用户确认关闭,调用Application.Current.Quit()主动退出应用,否则窗口保持打开状态。

内容的提问来源于stack exchange,提问作者F_CIL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 18:31:16