Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Application.Exit Event in WPF?

Tags:

I need to delete some certain files, then user closes program in WPF. So I tried MDSN code from here http://msdn.microsoft.com/en-us/library/system.windows.application.exit.aspx this way:

this code located here App.xml.cs

public partial class App : Application {  void App_Exit(object sender, ExitEventArgs e)     {        MessageBox.Show("File deleted");         var systemPath = System.Environment.GetFolderPath(                                   Environment.SpecialFolder.CommonApplicationData);                  var _directoryName1 = Path.Combine(systemPath, "RadiolocationQ");                 var temp_file = Path.Combine(_directoryName1, "temp.ini");                  if (File.Exists(temp1_file))                 {                     File.Delete(temp1_file);                 }      }  }  // App.xaml <Application x:Class="ModernUIApp1.App"              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"              StartupUri="MainWindow.xaml"              ShutdownMode="OnExplicitShutdown"              Exit="App_Exit">     <Application.Resources> 

First of all it doesn't delete files, secondly this program stays in the process after I pushed exit button( this is really strange). This code don't give any errors. And finally it doesn't show MessageBox So anything wrong here?

I think he just can`t find this function.

like image 960
Rocketq Avatar asked Dec 03 '13 09:12

Rocketq


People also ask

How to Exit Application in WPF?

We can close the window either by using "this. Close()"or by using "App. Current. Shutdown()".

How do I close all windows in WPF?

The proper way to shutdown a WPF app is to use Application. Current. Shutdown() . This will close all open Window s, raise some events so that cleanup code can be run, and it can't be canceled.


1 Answers

It's quite simple:

Add "Exit" property to the application tag

<Application x:Class="WpfApplication4.App"              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"              StartupUri="MainWindow.xaml"              Exit="Application_Exit"> </Application> 

and handle it in the "code behind"

private void Application_Exit(object sender, ExitEventArgs e) {     // Perform tasks at application exit } 

The Exit event is fired when the application is shutting down or the Windows session is ending. It is fired after the SessionEnding event. You cannot cancel the Exit event.

like image 163
Ofir Avatar answered Oct 18 '22 11:10

Ofir