65.9K
CodeProject is changing. Read more.
Home

How to know when the Task Manager kills your app

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.35/5 (10 votes)

Sep 17, 2007

CPOL

1 min read

viewsIcon

61129

downloadIcon

3748

Use a forked process to check when the Task Manager kills your app.

Screenshot - Diagram.jpg

Introduction

Hi everyone! This is my first CodeProject article! Whoa!

Today, I bring a solution to the problem of finding out in code when the Task Manager closes your application. I'm sure many of you out there have already figured out this one, but I couldn't find a good C# code for this, so here it is.

Background

On the FormClosing event of a Form, there is a FormClosingEventArgs which has a property that states the reason of the closing, named CloseReason. TaskManagerClosing is one of the possible reasons it gives.

But sadly, this method will only work if the user tries to close the application using the End Task button of the Applications tab. If, on the contrary, the user physically kills the process from the Processes tab, then the application dies a good death and never raises the FormClosing event (it's automatically removed from the OS's process table).

Using the code

I chose the "forking a process" pattern to avoid the creation of a second assembly. Although certainly, this, in a way, makes your code look kind of bloated.

Another solution would be to create a second executable, or perhaps a library, and have your helper code run there, but for simplicity's sake, this method is good enough.

This example creates a forked process that permanently checks the main process, and when it detects the main process's death, goes to check for the Task Manager being open, and then takes the desired action.

Actually, there must be a better way to check for the kill, maybe a catching a message on the Task Manager, or hooking to Task Manager. But, that would be an expert solution.