如何解决在Windows 11上运行的.Net Maui应用程序中关闭辅助窗口时未处理的异常

pbpqsu0x  于 6个月前  发布在  Windows
关注(0)|答案(1)|浏览(115)

在C# .NET Maui桌面应用程序中,当使用Application.Current.OpenWindow()打开多个窗口时,使用标题栏中的关闭按钮关闭窗口(不是主应用程序窗口)会在Windows 11中引发未处理的异常。
同样的代码在windows10中工作得很好。
在Windows 11中,当使用Application.Current.CloseWindow()从代码中关闭窗口时,情况也很好。
下面是一个简单程序的GitHub存储库来演示这个问题:https://github.com/Raminiya/MauiAppWindowTest
我发现了几个相同问题的报告,但没有解决方法。他们大多将问题与第二个窗口中的webview相关,并通过首先关闭webview来解决它。我在第二个窗口页面上没有任何特殊的问题。https://github.com/dotnet/maui/issues/7317中也建议了解决方法,但不起作用。
我还尝试使用以下代码覆盖关闭按钮函数:https://learn.microsoft.com/en-us/answers/questions/1384175/how-to-override-the-close-button-in-the-title-bar并简单地忽略事件,以便我可以从我的代码中关闭窗口,但是,在按下标题栏关闭按钮后(我忽略事件),然后当我使用Application.Current.CloseWindow()关闭窗口时,我会得到相同的异常。

zfycwa2u

zfycwa2u1#

虽然这个问题不会出现在所有的windows 11机器上,我不知道为什么,这里是解决方案:
通过将以下行添加到MauiProgram.cs中,可以调用函数
第一个月
问题已修复。(仅#If Windows和#endif之间的行。)

/// Need to use the 2 following name spaces:
#if WINDOWS 
using Microsoft.UI;
using Microsoft.UI.Windowing;
#endif

namespace MauiAppWindowTest
{
    public static class MauiProgram
    {
        public static bool NoTitleBar=false;
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                    fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                });
/// The Code below was added
#if WINDOWS
           builder.ConfigureLifecycleEvents(events =>
           {
               events.AddWindows(wndLifeCycleBuilder =>
               { 
                   wndLifeCycleBuilder.OnWindowCreated(window =>
                   {  
                          IntPtr nativeWindowHandle = WinRT.Interop.WindowNative.GetWindowHandle(window);
                          WindowId win32WindowsId = Win32Interop.GetWindowIdFromWindow(nativeWindowHandle);
                          AppWindow appWindow = AppWindow.GetFromWindowId(win32WindowsId);
                          if (appWindow.Presenter is OverlappedPresenter p)
                          {
                              /// Calling this function resolves the issue
                              p.SetBorderAndTitleBar(false, false);
                          }
                   });
               });
           });
#endif
/// Up to Here

            return builder.Build();
        }
    }
}

字符串

相关问题