7

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?

Mats Fredriksson
  • 19,783
  • 6
  • 37
  • 57

4 Answers4

10

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

Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
  • Doesn't seem to catch Ctrl-C though. Know anything about that? – Mats Fredriksson Nov 05 '09 at 11:35
  • 1
    @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 Nov 05 '09 at 12:35
1

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

andyp
  • 6,229
  • 3
  • 38
  • 55
  • I know how to shut down applications, I'm interested in how to attach events to when that happens. Thanks anyway tho. – Mats Fredriksson Nov 05 '09 at 11:37
  • 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 Nov 05 '09 at 11:46
  • Cool. Unfortunately I need it in console mode.. Probably should have mentioned that. – Mats Fredriksson Nov 05 '09 at 13:43
1

Maybe the answers to this may help you:

Community
  • 1
  • 1
Svish
  • 152,914
  • 173
  • 462
  • 620
  • 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 Nov 05 '09 at 11:39
  • 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 Nov 05 '09 at 14:21
0

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

Dave D
  • 8,472
  • 4
  • 33
  • 45