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

 荆怡婷151 发布于 2023-02-13 11:52

我需要删除一些某些文件,然后用户关闭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这里有什么不对吗?

我认为他无法找到这个功能.

2 个回答
  • 这很简单:

    将"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事件之后触发它.您无法取消退出事件.

    2023-02-13 11:55 回答
  • 你应该在你的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);
                }
    }
    

    2023-02-13 11:57 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有