tags:

views:

362

answers:

4

In c++ there is a function called atexit where you can register functions which should be run when the system exits. Are there any similar events in C#?

UPDATE: The AppDomain.ProcessExit doesn't seem to catch Ctrl-C or Ctrl-Break. Anyone knows anything about that?

+2  A: 

You can check the ProcessExit and DomainUnload events of the AppDomain class.

Fredrik Mörk
Doesn't seem to catch Ctrl-C though. Know anything about that?
Mats Fredriksson
@Mats: CTRL+C seems to close the process in some way that will not raise these events. That particular key combination do however raise the Console.CancelKeyPress event. So a combination of AppDomain.ProcessExit and Console.CancelKeyPress should cover most exit scenarios, I think.
Fredrik Mörk
A: 

If you're running a WinForms app you can add a listener to the Application.ApplicationExit event

Dave
A: 

There's the Application.ApplicationExit event if you've a WinForms application. For WPF there's Application.Exit.

andyp
I know how to shut down applications, I'm interested in how to attach events to when that happens. Thanks anyway tho.
Mats Fredriksson
Sorry, the one about the console app was wrong (I edited that). The two remaining references are events occuring when you exit your app (WinForm/WPF).
andyp
Cool. Unfortunately I need it in console mode.. Probably should have mentioned that.
Mats Fredriksson
+1  A: 

Maybe the answers to this may help you:

Svish
So probably need to catch both events then, the ProcessExit and the ConsoleCancelEventHandler. Would be neat with just one event that's always called. Well, well..
Mats Fredriksson
Could be. But that shouldn't be much of a problem, just do whatever you need to do in a separate method which is called by both eventhandlers or something :)
Svish