How to customise global window closing prompt in a .NET MAUI application

Arturs Pramalts 20 Reputation points
2024-05-28T08:55:28.29+00:00

I am working on a .NET MAUI project for desktop, I found a global solution for prompting a user before closing the application here.
I would like to know if this can be customised and triggered conditionally when closing.
For example: I have an EditorPage which has some entries etc. which are being checked for changes, if a user tries to exit the application when on this page with unsaved changes, the prompt should be triggered, else the app can close as normal with no prompt.
Here's an example of the global closing prompt in MauiProgram.cs, I want to replicate this with a single page conditionally:

            builder.ConfigureLifecycleEvents(events =>
                events.AddWindows(windowsLifecycleBuilder =>
                {
                    // Required for app title to appear on taskBar (as label)
                    windowsLifecycleBuilder.OnWindowCreated(window =>
                    {
                        var handle = WinRT.Interop.WindowNative.GetWindowHandle(window);
                        var id = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(handle);
                        var appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(id);
                        // appWindow.Title is used so that when the app is running there is a title which appears in the task bar, if this is not here it is blank.
                        appWindow.Title = "2Pint Config Editor";
                        appWindow.Closing += async (s, e) =>
                        {
                            e.Cancel = true;
                            bool result = await App.Current.MainPage.DisplayAlert(
                                "Exit prompt",
                                "Are you sure you want to exit the application?",
                                "Yes",
                                "Cancel"
                                );
                            if (result)
                            {
                                App.Current.Quit();
                            }
                        };
                    });
                }));

I would appreciate any suggestions on how to do this

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
4,020 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,337 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 81,011 Reputation points Microsoft External Staff
    2024-05-29T06:26:55.6+00:00

    Hello,

    I have an EditorPage which has some entries etc. which are being checked for changes, if a user tries to exit the application when on this page with unsaved changes, the prompt should be triggered, else the app can close as normal with no prompt.

    You can do this by get current appeared page and add a static flag in this specific page.

    For example, if you use Shell. you can get current appeared page by Page currentpage = AppShell.Current.CurrentPage;, if you use NavigationPage. you can get current page by Page currentpage = Application.Current.MainPage.Navigation.NavigationStack.Last();.

    And I add a static flag called IsSaved like following code.

    public partial class NewPage1 : ContentPage
    {
    	public static bool IsSaved=false;
    	public NewPage1()
    	{
    		InitializeComponent();
    	}
    }
    

    In the end, we can implement it in the MauiProgram.cs like following code.

         events.AddWindows(windowsLifecycleBuilder =>
                    {
    #if WINDOWS
                        // Required for app title to appear on taskBar (as label)
                        windowsLifecycleBuilder.OnWindowCreated(window =>
                        {
                            var handle = WinRT.Interop.WindowNative.GetWindowHandle(window);
                            var id = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(handle);
                            var appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(id);
                            // appWindow.Title is used so that when the app is running there is a title which appears in the task bar, if this is not here it is blank.
                            appWindow.Title = "2Pint Config Editor";
                            appWindow.Closing += async (s, e) =>
                            {
                                Page currentpage = AppShell.Current.CurrentPage;
                              //  Page currentpage //=Application.Current.MainPage.Navigation.NavigationStack.Last();       
                             if(currentpage is NewPage1 && NewPage1.IsSaved==false)
                                {
                                    var res = currentpage.GetType;
                                    //  if (res != null&& res.(NewPage1))
                                    e.Cancel = true;
                                    bool result = await App.Current.MainPage.DisplayAlert(
                                        "Exit prompt",
                                        "Are you sure you want to exit the application?",
                                        "Yes",
                                        "Cancel"
                                        );
                                    if (result)
                                    {
                                        App.Current.Quit();
                                    }
                                }
                            };
                        });
    #endif
                    })
    

    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.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.