no

How to Catch Closing Event of a Console Application in C#

On application closing we certainly always need to perform a clean up. But on the case of a c# console application there is no clear way to ...

On application closing we certainly always need to perform a clean up. But on the case of a c# console application there is no clear way to do it. And this is what I came up, to import a function from kernel32.dll, which is SetConsoleCtrlHandler.

I'll let my code explain the rest:
class Program
    {
        #region Page Event Setup
        enum ConsoleCtrlHandlerCode : uint
        {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT = 1,
            CTRL_CLOSE_EVENT = 2,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT = 6
        }
        delegate bool ConsoleCtrlHandlerDelegate(ConsoleCtrlHandlerCode eventCode);
        [DllImport("kernel32.dll")]
        static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandlerDelegate handlerProc, bool add);
        static ConsoleCtrlHandlerDelegate _consoleHandler;        
  #endregion

  public Program()
        {
            _consoleHandler = new ConsoleCtrlHandlerDelegate(ConsoleEventHandler);
            SetConsoleCtrlHandler(_consoleHandler, true);
        }
  
  #region Page Events
        bool ConsoleEventHandler(ConsoleCtrlHandlerCode eventCode)
        {
            // Handle close event here...
            switch (eventCode)
            {
                case ConsoleCtrlHandlerCode.CTRL_CLOSE_EVENT:
                case ConsoleCtrlHandlerCode.CTRL_BREAK_EVENT:
                case ConsoleCtrlHandlerCode.CTRL_LOGOFF_EVENT:
                case ConsoleCtrlHandlerCode.CTRL_SHUTDOWN_EVENT:
                    Destroy();
                    Environment.Exit(0);
                    break;
            }

            return (false);
        }
        #endregion
 }

Related

c# 964482753474626538

Post a Comment Default Comments

2 comments

Unknown said...

thanks ..it helped me...

Pradeep Puranik said...

This would have been an excellent solution. But unfortunately this is not working for me. I'm using Windows 8.1 with VS 2008, and the ConsoleEventHandler event never fires when I close the window by clicking the X button.

item