Posts Tagged '.net'

How To Catch “Kill” Events in a C# console application

The fist step to catch a kill event in a C#/.NET console application is to install a “ConsoleCtrlCheck” HandlerRoutine. The HandlerRoutine will be called whenever the user presses CTRL+C or clicking on the X to close the console window.

So we have to define a delegate type for the HandlerRoutine then and import SetConsoleCtrlHandler from Kernel32.dll.

using System.Runtime.InteropServices;
class Foobar
     #region unmanaged

        /// <summary>
        /// This function sets the handler for kill events.
        /// </summary>
        /// <param name="Handler"></param>
        /// <param name="Add"></param>
        /// <returns></returns>
        public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);

        //delegate type to be used of the handler routine
        public delegate bool HandlerRoutine(CtrlTypes CtrlType);

        // control messages
        public enum CtrlTypes
            CTRL_C_EVENT = 0,
            CTRL_LOGOFF_EVENT = 5,


Now we need to implement the handler function ConsoleCtrlCheck and define this function as our ConsoleCtrlHandler function in the main method.

        /// <summary>
        /// This method will be called if the user closes the console window or presses CTRL+C
        /// </summary>
        /// <param name="ctrlType"></param>
        /// <returns>always true</returns>
        private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
            // TODO: implement exit handler routine
            return true;

        static void Main(string[] args)

            HandlerRoutine hr = new HandlerRoutine(ConsoleCtrlCheck);
            // we have to keep the handler routine alive during the execution of the program,
            // because the garbage collector will destroy it after any CTRL event
            SetConsoleCtrlHandler(hr, true);