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.
MAUI DisplayAlert() When User Closes Window : Getting Unhandled Exception
Aftab Ali
1
Reputation point
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)
{
}
}
}