8

How can i know when my C# console application will be stopping? Is there any event or like that?

Thanks!

S2S2
  • 8,322
  • 5
  • 37
  • 65
Robert
  • 507
  • 2
  • 9
  • 20

2 Answers2

26

Use ProcessExit event of the application domain

   class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);           


        }

        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            Console.WriteLine("exit");
        }
    }
Habib
  • 219,104
  • 29
  • 407
  • 436
  • It should be noted that your code in CurrentDomain_ProcessExit will only be given a few seconds to execute before the application terminates anyway. – rory.ap Aug 24 '17 at 14:48
  • 1
    This will not help when user logs off or system reboots. See [here](https://stackoverflow.com/a/6799964/1051244). Since Console applications dont raise the SessionEnding event, add a hidden window to catch them. The hidden window can be inherited from System.Windows.Forms.Form and should be started in a seperate thread with Application.Run(myHiddenForm). In the load event of the form add your event handler to SystemEvents.SessionEnding which should gracefully stop your application. – huha Apr 17 '20 at 08:37
6

Handling the event System.Console.CancelKeyPress might help you.

MSDN explains it how to handle this event along with other things that you need to take care of while handling this event, excerpt:

This event is used in conjunction with System.ConsoleCancelEventHandler and System.ConsoleCancelEventArgs. The CancelKeyPress event enables a console application to intercept the CTRL+C signal so the application can decide whether to continue executing or terminate.

Use this event to explicitly control how your application responds to the CTRL+C signal. If your application has simple requirements, you can use the TreatControlCAsInput property instead of this event.

The event handler for this event is executed on a thread pool thread.

S2S2
  • 8,322
  • 5
  • 37
  • 65