SoFunction
Updated on 2025-03-06

Code instances that handle 2 closing events in C# console program

Application scenarios

The console application we developed is likely to be terminated by user Ctrl+C or directly closed by user during the run phase. If we do not want the user to terminate our program through Ctrl+C, we need to handle Ctrl+C or closing events.

How to deal with it

On the .net platform, the Console class has a CancelKeyPress event that can handle Ctrl+C, but there is nothing to do about directly closing the console application.

However, there is a SetConsoleCtrlHandler function in the Windows API that can handle these two kinds of shutdown events.

The C# processing code is as follows:

Copy the codeThe code is as follows:

static class Program
{
    public delegate bool ControlCtrlDelegate(int CtrlType);
    [DllImport("")]
    private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerRoutine, bool Add);
    private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerRoutine);

    public static bool HandlerRoutine(int CtrlType)
    {
        switch (CtrlType)
        {
            case 0:
("0 tool was forced to close"); //Ctrl+C close
                break;
            case 2:
("2 tools are forced to close");//Press the console close button to close
                break;
        }
        ();
        return false;
    } 

    /// <summary>
/// The main entry point of the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        SetConsoleCtrlHandler(cancelHandler, true);
        ();
    }
}