如何在WPF中使用Application.Exit事件?

我需要删除一些某些文件,然后用户关闭WPF中的程序。 所以我从这里尝试了MDSN代码http://msdn.microsoft.com/en-us/library/system.windows.application.exit.aspx这样:

此代码位于此处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   

首先它不删除文件,其次这个程序在我按下退出按钮后停留在这个过程中(这真的很奇怪)。 此代码不会给出任何错误。 最后它没有显示MessageBox所以这里有什么不对吗?

我想他只是找不到这个function。

这很简单:

将“Exit”属性添加到应用程序标记

   

并在“代码背后”处理它

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

应用程序关闭或Windows会话结束时会触发Exit事件。 在SessionEnding事件之后触发它。 您无法取消退出事件。

你应该在你的xaml代码中添加app_exit

    

你可以挂钩事件关闭你的主窗口像这样 –

   

在您的活动中,做您需要的所有工作

  private void Window_Closing(object sender, CancelEventArgs 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); } } 
  1. 确保命名空间(MyApp)与“x:Class = MyApp …”匹配
  2. 属性下,双击“Exit”旁边的文本框。
  3. 如果你得到“无法添加事件处理程序”,那么重建项目会为我修复它。

XAML

  

代码背后

 using System.Windows; namespace MyApp { public partial class App : Application { private void Application_Exit(object sender, ExitEventArgs e) { //your code } } }