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

如何在Mac上关闭MAUI项目时弹出确认询问框

在MAUI Mac项目中实现关闭确认弹窗

可以实现该功能,核心是通过Mac Catalyst原生API监听窗口关闭事件,以下是具体操作步骤:

1. 添加Mac平台特定代码

在项目的Platforms/MacCatalyst目录下,创建CustomWindowDelegate.cs文件,代码如下:

using AppKit;
using Foundation;

namespace YourAppName.Platforms.MacCatalyst;

public class CustomWindowDelegate : NSWindowDelegate
{
    public override bool WindowShouldClose(NSObject sender)
    {
        // 创建确认弹窗
        var alert = new NSAlert()
        {
            MessageText = "确认关闭",
            InformativeText = "您确定要关闭应用吗?",
            AlertStyle = NSAlertStyle.Warning
        };
        
        // 添加操作按钮
        alert.AddButton("是");
        alert.AddButton("否");
        
        // 显示弹窗并获取用户选择
        var result = alert.RunModal();
        
        // 返回true则关闭窗口,false则取消关闭
        return result == NSAlertButtonReturn.First;
    }
}

注意将YourAppName替换为你的项目实际命名空间。

2. 关联自定义Delegate到主窗口

打开Platforms/MacCatalyst/AppDelegate.cs(若没有该文件,右键MacCatalyst目录→添加→类→创建AppDelegate),修改代码如下:

using Foundation;
using Microsoft.Maui;
using Microsoft.Maui.Hosting;
using AppKit;

namespace YourAppName.Platforms.MacCatalyst;

[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate
{
    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();

    public override void DidFinishLaunching(NSNotification notification)
    {
        base.DidFinishLaunching(notification);
        
        // 获取主窗口并绑定自定义Delegate
        if (NSApplication.SharedApplication.MainWindow != null)
        {
            NSApplication.SharedApplication.MainWindow.Delegate = new CustomWindowDelegate();
        }
    }
}

3. 验证功能

运行Mac版本的MAUI应用,点击窗口左上角的红色关闭叉号,会弹出确认弹窗:

  • 点击「是」:应用正常关闭
  • 点击「否」:弹窗关闭,应用保持打开状态

补充说明

  • 该代码仅对Mac Catalyst平台生效,不会影响Windows、iOS等其他平台的行为
  • 可通过修改NSAlert的MessageText、InformativeText属性自定义弹窗文字,调整按钮文字或样式适配需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:32:43