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>
[DllImport("Kernel32")]
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_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
#endregion
....
}
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
GC.KeepAlive(hr);
SetConsoleCtrlHandler(hr, true);
....
}