tags:

views:

228

answers:

5

I want to execute some code (clear up resoucrse) on termination my WinFormsApplication using Windows TaskManager. How can I do it? I am terminating my application using Process Tab of TaskManager.

+2  A: 

Handle this event in your main app window:

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    if(e.CloseReason == CloseReason.TaskManagerClosing) {
        // clean up code
    }
}
Christian Hayter
@Christian Hayter, Your way is useless in my case, because I am terminating my application using Process Tab of TaskManager. See my edit
DreamWalker
You're a bit stuck really. The FormClosing event fires when it's closed from the Application tab because the Application tab sends a Windows quit message to the app's message loop. This gives the app a chance to execute code. If you close it from the Process tab, you terminate the process without executing any code. Therefore it is probably not possible to trap.
Christian Hayter
It is not possible because you terminate process...
Sasha
+4  A: 

Hookup the ApplicationExit event from your main form and do the cleanup there.

Edit: If you are closing the application through the task manager, there is no event that you can catch. These events are expecting normal termination processes.

Oded
I have tried it, but it doesn't work.
DreamWalker
How did you hook it up?
Oded
this event handler will not be called if you terminate it using taskmanager.
Benny
+4  A: 

If your application is forcibly closed I'm not sure there is a reliable way to ensure you clean up resources. I'm assuming your resources are non-standard ones that you, and not Windows, manage.

There are two possibilities. The first is to install a windows service application that watches your app and ensures its resources are cleaned up when your application is killed. This requires some inter-process communication and a fair amount of coding.

The second is to ensure resources are clean on application startup. Check to see if your resources are out there hanging around when you run, and clean them up before continuing execution.

Will
You may also want to consider why users need to end your process using the process tab in the first place.
Will Eddins
+1  A: 

I am not sure and I haven't tried it. But my guess is that it should be possible by trapping some Win32 events. Try WM_CLOSE, CTRL_CLOSE_EVENT

P.K
A: 

The CriticalFinalizerObject might help you according to its description:

... the common language runtime (CLR) guarantees that all critical finalization code will be given the opportunity to execute, provided the finalizer follows the rules for a CER, even in situations where the CLR forcibly unloads an application domain or aborts a thread

winSharp93