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.

        static void Main(string[] args)
            HandlerRoutine hr = new HandlerRoutine(Handler);
            SetConsoleCtrlHandler(hr, true);


        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:
            return true;

        // Declare the SetConsoleCtrlHandler function
        // as external and receiving a delegate.  
        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_LOGOFF_EVENT = 5,



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


Post a Comment

Popular posts from this blog

CSS text-overflow ellipsis in the beginning of the the text - Left Ellipsis using CSS in a Flex box

Selenium With .Net