0

I'm attempting to execute code on exit in a windows form application. In my Main() function, I've placed the following code:

Thread.GetDomain().UnhandledException += 
   (sender, eventArgs) => Exiting((Exception)eventArgs.ExceptionObject);

AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => Exiting(null);

Application.ApplicationExit += (sender, eventArgs) => Exiting(null);

This is what the Exiting() function looks like:

private static void Exiting(Exception exception)
{
   if (exception == null)
   {
      Console.WriteLine("normal proc exit");
   }
   else
   {
      Console.WriteLine("unhandled exception: " + exception.GetType().Name);
   }
}

However, it hasn't written the expected console line even once while debugging. What is the proper way to do this?

Fibericon
  • 5,684
  • 12
  • 37
  • 64
  • If it is a Windows Form application, what console are you expecting it to write to? – mjwills Jul 22 '17 at 11:31
  • @mjwills The debug console in Visual Studio. – Fibericon Jul 22 '17 at 11:33
  • Have you set a breakpoint in your method to make sure that it is executing on exit? – Ben Jul 22 '17 at 12:14
  • I've made a sample project with your code and it's working like expected. Message is shown in the output window of visual studio. – Ben Jul 22 '17 at 12:18
  • @Ben It does not appear to be executing this method on exit, and the breakpoint is never reached. Could the problem be that I'm using the stop debug button to end the program? – Fibericon Jul 22 '17 at 12:20
  • 2
    Here is a similiar question https://stackoverflow.com/questions/11023944/stop-debugging-event-in-c-sharp – Ben Jul 22 '17 at 12:22
  • @Fibericon try to close the application with the cross and check if this works also check my answer , maybe this is the problem – Sybren Jul 22 '17 at 12:25

0 Answers0