MAUI DisplayAlert() When User Closes Window : Getting Unhandled Exception

Aftab Ali 1 Reputation point
2022-08-11T15:32:25.757+00:00

I want to show an ALERT/POPUP to the user to ask him/her before he closes the Application.

This is what I am already doing :

In App.xaml.cs

Application.Current.MainPage.DisplayAlert this line throws unhandled exception,
The Exception gets unhandled by debugger itself. and it says :

a debugger is attached to but not configured to debug this unhandled
exception.

https://github.com/BhangeeF16/MAUI-DOT-NET/blob/main/SampleApp/App.xaml.cs

    public partial class App : Application  
    {  
    	public static IServiceProvider Services;  
      
        public App(IServiceProvider serviceProvider)  
        {  
            InitializeComponent();  
            Services = serviceProvider;  
            MainPage = new MainPage();  
        }  
        protected override Window CreateWindow(IActivationState activationState)  
        {  
            Window window = base.CreateWindow(activationState);  
            window.Page = MainPage;  
            window.Destroying += Window_Destroying;  
            return window;  
        }  
      
        private void Window_Destroying(object sender, EventArgs e)  
        {  
            try  
            {  
                System.Diagnostics.Debug.WriteLine("Destroying");  
                App.Current.Dispatcher.Dispatch(async () =>  
                await App.Current.MainPage.DisplayAlert("Alert", "Are you sure you want to close the application.", "Yes", "No"));      
            }  
            catch (Exception)  
            {  
            }  
        }  
    }  
  
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,883 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.
10,260 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
764 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,286 Reputation points
    2022-08-12T00:37:51.47+00:00

    It does not make sense to pop up an alert from a destroyed window, the handle will not be valid. The destroy event is for releasing resources.