/// <summary> /// Initializes a new instance of the <see cref="SafeTerminateHandler{T}"/> class that /// wraps a disposable object that will be created by calling the /// specified callback Func. /// </summary> /// <param name="createCallback">A method that has no parameters and returns a new disposable object of the type specified by the <typeparamref name="T"/> parameter.</param> public SafeTerminateHandler(Func <T> createCallback) { _disposedValue = true; _lock = new object(); BaseDisposableObject = null; _HandlerRoutine = (Kernel32.CtrlTypes dwCtrlType) => { switch (dwCtrlType) { case Kernel32.CtrlTypes.CTRL_C_EVENT: case Kernel32.CtrlTypes.CTRL_BREAK_EVENT: case Kernel32.CtrlTypes.CTRL_CLOSE_EVENT: Dispose(); break; default: break; } return(false); }; lock (_lock) { _disposedValue = false; if (!Kernel32.SetConsoleCtrlHandler(_HandlerRoutine, true)) { throw new Exception("SetConsoleCtrlHandler failed to add handler."); } BaseDisposableObject = createCallback(); } }
public static void AddConsoleEventHandler(Kernel32.PHANDLER_ROUTINE handler) { try { Kernel32.SetConsoleCtrlHandler(handler, true); } catch (Exception ex) when(IsDllException(ex)) { } }