In a console application I developed, I use FiddlerCore to intercept HTTP requests. FiddlerCore modifies Windows network settings, so the original settings must be restored before the application exits. In .NET, you can handle Ctrl+C and Ctrl+Break via Console.CancelKeyPress, which is the standard approach. However, users can also close the console window directly, which kills the process without firing CancelKeyPress. In that case, your cleanup code will not run.
Windows provides SetConsoleCtrlHandler, which handles all console control events: Ctrl+C, Ctrl+Break, and the console close event. Call it at startup to ensure cleanup always runs. Here's the complete code:
C#
class Program
{
// https://learn.microsoft.com/en-us/windows/console/setconsolectrlhandler?WT.mc_id=DT-MVP-5003978
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(SetConsoleCtrlEventHandler handler, bool add);
// https://learn.microsoft.com/en-us/windows/console/handlerroutine?WT.mc_id=DT-MVP-5003978
private delegate bool SetConsoleCtrlEventHandler(CtrlType sig);
private enum CtrlType
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
static void Main(string[] args)
{
// Register the handler
SetConsoleCtrlHandler(Handler, true);
// Wait for the event
while (true)
{
Thread.Sleep(50);
}
}
private static bool Handler(CtrlType signal)
{
switch (signal)
{
case CtrlType.CTRL_BREAK_EVENT:
case CtrlType.CTRL_C_EVENT:
case CtrlType.CTRL_LOGOFF_EVENT:
case CtrlType.CTRL_SHUTDOWN_EVENT:
case CtrlType.CTRL_CLOSE_EVENT:
Console.WriteLine("Closing");
// TODO Cleanup resources
Environment.Exit(0);
return false;
default:
return false;
}
}
}
Do you have a question or a suggestion about this post? Contact me!