1

I have a C# application that consists of multiple forms, and there is no particular one which will always be closed last.

Where should I put a piece of code (i.e. dumping some information to a file) to ensure that no matter how the program exits, this happens just before the program closes?

Adam
  • 311
  • 1
  • 3
  • 15
  • The app domain process exit? http://stackoverflow.com/questions/18033100/unload-event-for-the-default-application-domain – David Brabant Jul 25 '14 at 14:00
  • The only scenarios you'll be able to account for are any "natural" closing of the program. Closing the program in Task Manager, or a power fault to the computer (pushing the power button or losing power) are two scenarios you can't do anything about. Task Manager could be a real concern, especially if your "closing code" is something that takes a really long time. – krillgar Jul 25 '14 at 14:01
  • See [this answer](http://stackoverflow.com/a/2555354) – Ken White Jul 25 '14 at 14:04
  • WinForms, and I suppose I could do without it for stuff like killing the process in task manager, but definitely would like it for every natural closing of the program. Is there a particular place to put this code? – Adam Jul 25 '14 at 14:12

1 Answers1

1

Well one option would be to call a method to do what ever you want right before the main method exits.

ETA:

by default the main method is in the program.cs file.

here is an example of what I mean

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());

        //** this code will not be reached until form1 closes.
        bool blah = true;
        doWhatEver(blah);
    }
TheColonel26
  • 2,618
  • 7
  • 25
  • 50