Handling Exit Event of Console Application in C#

Do you wan to do something on the exit event of Console Application. .Net framework does not provide such direct event to do that. You can use following workaround to have that kind of event in your application.


        [STAThread]
        static void Main(string[] args)
        {
            HandlerRoutine hr = new HandlerRoutine(Handler);
            SetConsoleCtrlHandler(hr, true);
            GC.KeepAlive(hr); 

        }

        public static void DoOnAppExit()
        {
                  //Do something......
        }

        #region Handle App Exit

        static Boolean Handler(CtrlTypes CtrlType)
        {
            // A switch to handle the event type.
            switch (CtrlType)
            {
                case CtrlTypes.CTRL_C_EVENT:
                case CtrlTypes.CTRL_BREAK_EVENT:
                case CtrlTypes.CTRL_CLOSE_EVENT:
                case CtrlTypes.CTRL_LOGOFF_EVENT:
                case CtrlTypes.CTRL_SHUTDOWN_EVENT:
                    DoOnAppExit();
                    break;
            }
            return true;
        }


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

        // A delegate type to be used as the handler routine
        // for SetConsoleCtrlHandler.
        public delegate Boolean 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

Comments

  1. Thanks a Lot.... This really works and saved a lot of time of mine....

    ReplyDelete

Post a Comment

Popular posts from this blog

Embedding PowerBI with ASP.NET Core 2 and Angular(2,4,5)

Taxi - Cab services in Colombo - Sri Lanka