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

pbpqsu0x  于 2023-11-21  发布在  Windows
关注(0)|答案(1)|浏览(291)

在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之间的行。)

  1. /// Need to use the 2 following name spaces:
  2. #if WINDOWS
  3. using Microsoft.UI;
  4. using Microsoft.UI.Windowing;
  5. #endif
  6. namespace MauiAppWindowTest
  7. {
  8. public static class MauiProgram
  9. {
  10. public static bool NoTitleBar=false;
  11. public static MauiApp CreateMauiApp()
  12. {
  13. var builder = MauiApp.CreateBuilder();
  14. builder
  15. .UseMauiApp<App>()
  16. .ConfigureFonts(fonts =>
  17. {
  18. fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
  19. fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
  20. });
  21. /// The Code below was added
  22. #if WINDOWS
  23. builder.ConfigureLifecycleEvents(events =>
  24. {
  25. events.AddWindows(wndLifeCycleBuilder =>
  26. {
  27. wndLifeCycleBuilder.OnWindowCreated(window =>
  28. {
  29. IntPtr nativeWindowHandle = WinRT.Interop.WindowNative.GetWindowHandle(window);
  30. WindowId win32WindowsId = Win32Interop.GetWindowIdFromWindow(nativeWindowHandle);
  31. AppWindow appWindow = AppWindow.GetFromWindowId(win32WindowsId);
  32. if (appWindow.Presenter is OverlappedPresenter p)
  33. {
  34. /// Calling this function resolves the issue
  35. p.SetBorderAndTitleBar(false, false);
  36. }
  37. });
  38. });
  39. });
  40. #endif
  41. /// Up to Here
  42. return builder.Build();
  43. }
  44. }
  45. }

字符串

展开查看全部

相关问题