I'm trying to open a ContentDialog
when the app is closing to prevent loosing unsafed data.
I managed to get the Closing
event:
public partial class App : Application
{
public IHost Host
{
get;
}
public static T GetService<T>() where T : class
{
if ((App.Current as App)!.Host.Services.GetService(typeof(T)) is not T service)
{
throw new ArgumentException($"{typeof(T)} needs to be registered in ConfigureServices within App.xaml.cs.");
}
return service;
}
public static WindowEx MainWindow { get; } = new MainWindow();
public static UIElement? AppTitlebar { get; set; }
public App()
{
InitializeComponent();
Host = Microsoft.Extensions.Hosting.Host.
CreateDefaultBuilder().
UseContentRoot(AppContext.BaseDirectory).
ConfigureServices((context, services) =>
{
// Default Activation Handler
services.AddTransient<ActivationHandler<LaunchActivatedEventArgs>, DefaultActivationHandler>();
...
}).
Build();
UnhandledException += App_UnhandledException;
}
private void App_UnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
{
}
protected async override void OnLaunched(LaunchActivatedEventArgs args)
{
IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(MainWindow);
WindowId windowId = Win32Interop.GetWindowIdFromWindow(hWnd);
AppWindow appWindow = AppWindow.GetFromWindowId(windowId);
if (appWindow != null)
{
appWindow.Closing += AppWindow_Closing;
}
base.OnLaunched(args);
await App.GetService<IActivationService>().ActivateAsync(args);
}
private async void AppWindow_Closing(AppWindow sender, AppWindowClosingEventArgs args)
{
ContentDialog contentDialog = new ContentDialog()
{
Title = "title...",
Content = "content...",
CloseButtonText = "Close"
};
contentDialog.XamlRoot = MainWindow.Content.XamlRoot;
await contentDialog.ShowAsync();
args.Cancel = false; // Set to true => prevents the application to close.
}
}
But the Dialogbox is not showing up.
In Debugmode I get an exception: System.Runtime.InteropServoces.COMException
Do you have any ideas how to solve that issue? I already searched the whole day in the net, but coulnd't find a solution