Search code examples
buttonblazormauihybrid

How to edit the function of the close button on MAUI Blazor Hybrid


I am working on an application written in MAUI Blazor. I would like that after click on the red button "Close", to bring up the message "Are you sure you want to close the application?". How to modify the function of the close system button on Windows? I tried used OnClosed event but I don't know how to use it correctly.

#if WINDOWS
            events.AddWindows(wndLifeCycleBuilder =>
            {
                wndLifeCycleBuilder.OnClosed((window, args) => LogEvent("OnClosed"));

                wndLifeCycleBuilder.OnWindowCreated(window =>
                {
                    //Set size and center on screen using WinUIEx extension method
                    window.CenterOnScreen(400, 750);
                    window.ExtendsContentIntoTitleBar = true;
                });
            });

#endif

Close button

I mean this button.


Solution

  • Here

    #if WINDOWS
    events.AddWindows(windowsLifecycleBuilder =>
    {
        windowsLifecycleBuilder.OnWindowCreated(window =>
        {
            //we need this to use Microsoft.UI.Windowing functions for our window
            var handle = WinRT.Interop.WindowNative.GetWindowHandle(window);
            var id = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(handle);
            var appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(id);
    
            //and here it is
            appWindow.Closing += async (s, e) => 
            {
                e.Cancel = true;
                bool result = await App.Current.MainPage.DisplayAlert(
                    "Alert title", 
                    "You sure want to close app?", 
                    "Yes", 
                    "Cancel");
    
                if (result)
                {
                    App.Current.Quit();
                }
            };
        });
    });
    #endif