我需要删除一些某些文件,然后用户关闭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
这里有什么不对吗?
我认为他无法找到这个功能.
这很简单:
将"Exit"属性添加到应用程序标记
<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>
并在"代码背后"处理它
private void Application_Exit(object sender, ExitEventArgs e) { // Perform tasks at application exit }
应用程序关闭或Windows会话结束时会触发Exit事件.在SessionEnding事件之后触发它.您无法取消退出事件.
你应该在你的xaml代码中添加app_exit
<Application x:Class="CSharp.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>
你可以挂钩事件关闭你的主窗口像这样 -
<Window Closing="Window_Closing">
在您的活动中,做您需要的所有工作
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); } }