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

.NET MAUI中如何阻止用户关闭主窗体并转为最小化?

在.NET MAUI中阻止窗口关闭并最小化应用的实现方法

在.NET MAUI里,OnDisappearing是页面生命周期事件,仅在页面切换时触发,和窗口关闭操作无关,所以没法用它实现阻止窗口关闭的需求。要实现类似WinForms中点击「X」按钮时最小化而非关闭应用的功能,需要针对Windows平台绑定原生窗口的Closing事件,具体实现如下:

实现步骤

  1. 用条件编译仅针对Windows平台编写代码(该需求仅适配桌面Windows场景)
  2. 获取MAUI窗口对应的WinUI原生窗口实例
  3. 绑定原生窗口的Closing事件,在事件处理中取消关闭操作并将窗口最小化

代码示例

在App.xaml.cs中添加以下代码:

protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    base.OnLaunched(args);

    #if WINDOWS
    var currentWindow = Application.Current.Windows.FirstOrDefault();
    if (currentWindow != null)
    {
        // 获取Windows原生WinUI窗口实例
        var nativeWindow = currentWindow.Handler.PlatformView as Microsoft.UI.Xaml.Window;
        // 绑定Closing事件
        nativeWindow.Closing += NativeWindow_Closing;
    }
    #endif
}

#if WINDOWS
private void NativeWindow_Closing(object sender, Microsoft.UI.Xaml.WindowEventArgs e)
{
    // 取消窗口关闭操作
    e.Handled = true;
    // 将MAUI窗口切换为最小化状态
    var mauiWindow = Application.Current.Windows.FirstOrDefault();
    if (mauiWindow != null)
    {
        mauiWindow.WindowState = WindowState.Minimized;
    }
}
#endif

代码说明

  • #if WINDOWS:确保代码仅在Windows平台编译执行,避免干扰其他平台的运行逻辑
  • currentWindow.Handler.PlatformView:MAUI窗口的Handler属性包含平台原生视图的引用,转换为WinUI的Window类型即可访问原生窗口事件
  • e.Handled = true:标记关闭事件已处理,阻止系统执行默认的窗口关闭逻辑
  • mauiWindow.WindowState = WindowState.Minimized:通过MAUI的窗口对象设置最小化状态,无需直接操作原生窗口

内容的提问来源于stack exchange,提问作者Dika Arta Karunia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:22:29