Is there a way to intercept the kill command on Windows (.NET)?

I have a Windows console application written in .NET 4.0 (C #) and if the application / process is killed abnormally (e.g. from the task manager or shutting down the operating system), is there a way to intercept this so that some cleanup code can be executed?

Thanks for any help.


source to share

3 answers

Take a look at Win32.SystemEvents , there are good examples of how to detect these events.



You cannot find that your own process is killed. When someone calls NtTerminateProcess () with your process and they have permission to do so, you are not informed. Your threads stop and your process disappears from under you.

Fortunately, most of the cleanup doesn't need to be done manually - all that memory that you didn't free will be fixed by the OS, all those system descriptors that you didn't close will be automatically cleaned up, and any temporary files you opened as TEMPORARY ( are you doing it right?) will be automatically deleted.

The reason is simple. If you decide to kill the program through the task manager - this is because the user decided that it was wrong. If you then tell it to stop the wrong behavior, it might be ignoring you because, well, that’s bad.

It seems like the best way for you to control the process is to provide you with a legal way to exit the process - whether through a window that handles the WM_CLOSE event or fire it in the console, which can be interrupted by the red-X button in the corner. The task manager should be a last resort. If the user has a problem with Ctrl + Alt + Del your process to death, you won't get a second chance.



There is usually no way to handle the process that is being killed, but you should be able to handle events that are raised when the application exits. (Think: if you could handle a process that got killed, it would be really very easy to write some horrible stuff like spyware). If I remember correctly, there is a way to check why the application is closing. Depending on what is causing it to close, you may react differently.



All Articles