Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how to receive system close or exit events in a commandline application [duplicate]

I'm trying, but everything I've found so far seems to centre around GUI's and form apps. That is not what I'm using.

Eventually it'll be a service, but till it is done I'm running it as a normal app, the problem being that if I just close it by accident, it'll leave another service hanging for up to 30 minutes with bad data. I though it would be easy to add a listener to catch the app being closed.

But I just can't figure it out.

like image 458
A.Grandt Avatar asked Feb 20 '23 11:02

A.Grandt


1 Answers

Here you have a perfect solution for what you need:

Detecting console application exit in c#

The code detects all the possible events that will close the application:

  • Control+C
  • Control+Break
  • Close Event ("normal" closing of the program, with Close Button)
  • Logoff Event (use logging off)
  • Shutdown Event (system closing)
namespace Detect_Console_Application_Exit2
{
  class Program
  {
    private static bool isclosing = false;

    static void Main(string[] args)
    {
      SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);
      Console.WriteLine("CTRL+C,CTRL+BREAK or suppress the application to exit");
      while (!isclosing) ;
    }

    private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
    {
      // Put your own handler here
      switch (ctrlType)
      {
        case CtrlTypes.CTRL_C_EVENT:
          isclosing = true;
          Console.WriteLine("CTRL+C received!");
          break;

        case CtrlTypes.CTRL_BREAK_EVENT:
          isclosing = true;
          Console.WriteLine("CTRL+BREAK received!");
          break;

        case CtrlTypes.CTRL_CLOSE_EVENT:
          isclosing = true;
          Console.WriteLine("Program being closed!");
          break;

        case CtrlTypes.CTRL_LOGOFF_EVENT:
        case CtrlTypes.CTRL_SHUTDOWN_EVENT:
          isclosing = true;
          Console.WriteLine("User is logging off!");
          break;
      }
      return true;
    }

    #region unmanaged

    // Declare the SetConsoleCtrlHandler function
    // as external and receiving a delegate.
    [DllImport("Kernel32")]
    public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);

    // A delegate type to be used as the handler routine
    // for SetConsoleCtrlHandler.
    public delegate bool HandlerRoutine(CtrlTypes CtrlType);

    // An enumerated type for the control messages
    // sent to the handler routine.
    public enum CtrlTypes
    {
      CTRL_C_EVENT = 0,
      CTRL_BREAK_EVENT,
      CTRL_CLOSE_EVENT,
      CTRL_LOGOFF_EVENT = 5,
      CTRL_SHUTDOWN_EVENT
    }

    #endregion

    }
}
like image 185
JotaBe Avatar answered Apr 26 '23 09:04

JotaBe