WinForm 应用程序 -> 结束进程 -> 未触发 FormClosing() 和 FormClosed() 事件

WinForm Application -> End Process -> FormClosing() & FormClosed() events Not Fired

我有一个启动的 win-form 应用程序,在 FormClosing() & FormClosed() 事件中有一些代码。
对于另一个应用程序,我想像这样强行关闭第一个应用程序:

    string procId = proc.Id.ToString();

    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.FileName = "taskkill.exe";
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.Arguments = "/f /t /pid " + procId;
    Process.Start(startInfo);

当我想通过这些代码强制关闭第一个应用程序或使用 Task Manager -> End Process , FormClosing() & FormClosed() 事件未触发。

我怎样才能在所有情况下强制触发这些事件或者解决方案是什么?

参见Prevent C# app from process kill

您无法阻止您的应用进程被终止,并且您不会收到它正在终止的事件。

因此,您必须考虑到进程在关闭时没有很好地清理的情况。就此而言,无论如何您都需要这样做,如果您的应用程序处于 运行 时机器出现蓝屏死机怎么办?您永远不能假设前一个实例已成功完成。

您的应用似乎在关机时关闭了一些数据文件,以便程序下次运行时可以再次读取该文件。如果是这种情况,您可以在文件中或附近写一些“脏标志”,如果它被标记,则在启动时清理文件。

How does task manager kill my program? and MSDN: Terminating a Process (Windows) 中所述:

Note that you cannot intercept or react upon TerminateProcess. Your process will die and there is nothing you can do before that happens.

If a process is terminated by TerminateProcess, all threads of the process are terminated immediately with no chance to run additional code. This means that the thread does not execute code in termination handler blocks.