Within a C# .NET Maui Desktop Application, when multiple windows are opened using
Application.Current.OpenWindow()
, closing a window (not the primary application window) using the close button in the title bar raises an unhandled Exception in Windows 11.
The same code works perfectly fine in windows 10.
Also things are fine in Windows 11 when the window is closed from within the code using
Application.Current.CloseWindow()
.
Here is a GitHub repository for a simple program to demonstrate this problem: https://github.com/Raminiya/MauiAppWindowTest
I found several reports of the same issue with no workarounds. They mostly related the issue to having a webview in the second window and resolved it by closing the webview first. I have the issue with nothing special on the second window page. A work around was also suggested in https://github.com/dotnet/maui/issues/7317 but did not work.
I've also tried to override the close button function using the following code:
https://learn.microsoft.com/en-us/answers/questions/1384175/how-to-override-the-close-button-in-the-title-bar
And simply ignore the event so I can close the Window from within my code but, after the title bar close button is pressed (And I ignore the event) then when I close the window using Application.Current.CloseWindow()
I'll get the same exception.(only on windows 11)
Although the issue dose not appear on all windows 11 machines and I don't know why, here is the solution:
By adding the following lines to the MauiProgram.cs to be able to call the function
SetBorderAndTitleBar(false, false);
the problem was fixed. ( Just the lines between #If Windows and #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();
}
}
}