Skip to content

Instantly share code, notes, and snippets.

@redmanmale
Created September 27, 2016 11:59
Show Gist options
  • Save redmanmale/8d19c2fd29bce652a8c034922a7dc90c to your computer and use it in GitHub Desktop.
Save redmanmale/8d19c2fd29bce652a8c034922a7dc90c to your computer and use it in GitHub Desktop.
Interceptor of console shutdown event. Could give you 5 sec to cleanup your mess (make some logging) before OS kills app.
public class ConsoleShutdown
{
[DllImport("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler(ControlEventHandler e, bool add);
public enum ConsoleEvent
{
CTRL_C = 0, // From wincom.h
CTRL_BREAK = 1,
CTRL_CLOSE = 2,
CTRL_LOGOFF = 5,
CTRL_SHUTDOWN = 6
}
public delegate bool ControlEventHandler(ConsoleEvent consoleEvent);
public event ControlEventHandler ShutdownEvent;
// Save delegate so the GC doesn't collect it.
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
private readonly ControlEventHandler _eventHandler;
public ConsoleShutdown()
{
// save this to a private var
// so the GC doesn't collect it...
_eventHandler = Handler;
SetConsoleCtrlHandler(_eventHandler, true);
}
private bool Handler(ConsoleEvent consoleEvent)
{
ShutdownEvent?.Invoke(consoleEvent);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment