Search code examples
c#.netwinformsprocessformclosing

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


I have a started win-form application with some codes in FormClosing() & FormClosed() events.
With another application i want to forcibly close that first application like this :

    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);

When i want for forcibly close first application by those codes or using with Task Manager -> End Process , FormClosing() & FormClosed() events are not fired.

How can i force those events to fire in every situation or what is the solution?


Solution

  • See Prevent C# app from process kill.

    You cannot prevent your app's process being terminated, and you won't get an event it is being terminated.

    So you must cater for the case where a process didn't clean up nicely at shutdown. For that matter, you need to do that anyway, what if the machine BSODs while your app is running? You can never assume the previous instance completed successfully.

    It looks like your app closes some data file upon shutdown, so that the next time the program runs it can read the file again. If that is the case, you could write some "dirty flag" in or near the file and clean the file up on startup if it is flagged.

    As explained in 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.