Search code examples
mauipopupwindow

How to create a pop-up question while closing MAUI project on Mac


While closing the MAUI project on Mac (clicking the red cross) I need it to ask a question if I really want to close the project and when clicking ‘yes’ it closes, by clicking ‘no’ it stays open. How can I do that if it’s possible?

red cross image

Thank you!


Solution

  • You want to implement a Close Confirmation with a MAUI Mac App. It needs to keep tracking the states of the open windows and when there is only one left, it shows alert to close the app. You may need to get this done in AppDelegate.cs under Platforms\MacCatalyst like below:

    private void Window_WillClose(object sender, System.EventArgs e)
    {
             openWindows.Remove((NSWindow)((NSNotification)sender).Object);
             if (openWindows.Count == 0)
             {
                  var confirmation = new NSAlert()
                    {
                        AlertStyle = NSAlertStyle.Warning,
                        InformativeText = "Do you want to exit the app?",
                        MessageText = "Exit?"
                    };
                    confirmation.AddButton("Yes");
                    confirmation.AddButton("No");
                    var result = confirmation.RunModal();
    
                    if (result == 1001)
                    {
                        this.closeApp = false;
                    }
                    else
                    {
                        //terminate the app
                        this.closeApp = true;
                   }
            }
    }
    

    Similar to MAUI Mac, please refer to this answered thread: How to do a Close Confirmation with a Xamarin Forms mac App?, if there's any issue, don't hesitate to report to githu:https://github.com/dotnet/maui/issues