Created
October 6, 2021 17:19
-
-
Save rjmholt/25b0ca56a3f9954945d0216786195263 to your computer and use it in GitHub Desktop.
Window close handler (for PowerShell)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CloseHandler : IModuleAssemblyInitializer | |
{ | |
public void OnImport() | |
{ | |
SetConsoleCtrlHandler(OnControlCode, add: true); | |
} | |
private static bool OnControlCode(CtrlType ctrlType) | |
{ | |
switch (ctrlType) | |
{ | |
case CtrlType.CTRL_CLOSE_EVENT: | |
case CtrlType.CTRL_LOGOFF_EVENT: | |
case CtrlType.CTRL_SHUTDOWN_EVENT: | |
// TODO: Remove Console.Beep() and replace it with your required action | |
Console.Beep(); | |
break; | |
} | |
return false; | |
} | |
[DllImport("kernel32.dll")] | |
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate handlerRoutine, bool add); | |
private delegate bool ConsoleCtrlDelegate(CtrlType ctrlType); | |
private enum CtrlType : uint | |
{ | |
CTRL_C_EVENT = 0, | |
CTRL_BREAK_EVENT = 1, | |
CTRL_CLOSE_EVENT = 2, | |
CTRL_LOGOFF_EVENT = 3, | |
CTRL_SHUTDOWN_EVENT = 4, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment