【发布时间】:2020-05-23 04:28:32
【问题描述】:
如果表单/应用程序(在本文中讨论我使用 WinForms 在 C# 中创建了我自己的表单/应用程序)由于某种原因没有被用户关闭,例如 PC 突然关机或防病毒应用程序关闭我的应用程序,在这种情况下,当应用程序关闭时,我需要在同一个应用程序中创建您写入应用程序关闭原因的文件。 我有一个想法在 FormClosing 事件处理程序或 FormClosed 中创建一个文件,以便在 (FormClosingEventArgs)e.CloseReason 中写入原因,但它没有用......我决定通过 KillProcess 程序测试它(我用这个程序,因为例如,如果我通过 Windows 任务管理器停止应用程序,那么文件将被写入用户自己停止应用程序,所以我需要软件,以便我的应用程序不会确定我关闭它),关闭程序,但我的应用程序甚至没有时间闪烁,并不是说它会创建一个文件并在那里写入关于终止原因的数据,一般来说,它不会创建或写入任何东西。 执行此任务的选项有哪些?我需要一个应用来完成这一切,也就是说,不需要其他应用来分析我的应用。
带有处理程序的代码:
private void UserForm_FormClosing(object sender, FormClosingEventArgs e)
{
Console.WriteLine("Closing!!!");
string path = @"C:\Users\Kulic\Desktop\reasonclose.txt";
FileInfo fileInf = new FileInfo(path);
switch (e.CloseReason)
{
case CloseReason.None:
{
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("The reason for the closure was not determined or cannot be determined.");
}
}
break;
}
case CloseReason.WindowsShutDown:
{
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("The operating system closes all applications before shutting down.");
}
}
break;
}
case CloseReason.MdiFormClosing:
{
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("The parent form of this multi-document interface (MDI) form is closed.");
}
}
break;
}
case CloseReason.UserClosing:
{
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("The form is closed programmatically or through user action in the UI (such as clicking the Close button in the window forms, select Close in the system menu of the window or by pressing ALT+F4).");
}
}
break;
}
case CloseReason.TaskManagerClosing:
{
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Microsoft Windows task Manager closes the application.");
}
}
break;
}
case CloseReason.FormOwnerClosing:
{
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("The owner form is closed.");
}
}
break;
}
case CloseReason.ApplicationExitCall:
{
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("The Exit() method of the Application class was called.");
}
}
break;
}
default:
{
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("The reason for closing was not revealed");
}
}
break;
}
}
}
【问题讨论】: