Hello,
You can do this by following steps.
Firstly, please set a title for second windows, we will use this title name to get the second windows in the MauiProgram.cs
NewPage3 newPage3 = new NewPage3();
Window MyWin = new Window(newPage3);
MyWin.Title = "MyWin";
Application.Current.OpenWindow(MyWin);
Next, please open MauiProgram.cs
and add ConfigureLifecycleEvents
for builder in the CreateMauiApp
method. Based on the title name, we can get the second window, if user click the close button in the titlebar, this appWindow.Closing
event will be executed.
When the user executes the closing event, we can push a display alert. If the user clicks Yes, close this application; if they click the Cancel, the display alert will dismiss. Here is a simple code that you can refer to.
var builder = MauiApp.CreateBuilder();
builder.ConfigureLifecycleEvents(events =>
{
#if WINDOWS
events.AddWindows(windowsLifecycleBuilder =>
{
windowsLifecycleBuilder.OnWindowCreated(window =>
{
if (window.Title== "MyWin")
{
//get the Secondary window title named "MyWin"
var windows = window;
//use Microsoft.UI.Windowing functions for window
var handle = WinRT.Interop.WindowNative.GetWindowHandle(window);
var id = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(handle);
var appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(id);
//When user execute the closing method, we can push a display alert. If user click Yes, close this application, if click the cancel, display alert will dismiss.
appWindow.Closing += async (s, e) =>
{
e.Cancel = true;
//get all of Microsoft.Maui.Controls.windows.
var windows1 = Application.Current.Windows.ToList<Microsoft.Maui.Controls.Window>();
foreach (Window win in windows1) {
//get the Secondary window title named "MyWin"
if (win.Title== "MyWin")
{
bool result = await win.Page.DisplayAlert(
"Alert title",
"You sure want to close app?",
"Yes",
"Cancel");
if (result)
{
Application.Current.CloseWindow(win);
}
}
}
};
}
});
});
#endif
})
.UseMauiApp<App>()
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.