From e678002744a8562b4d730f68c2dd2fb58f3ac44d Mon Sep 17 00:00:00 2001 From: Callum Watson Date: Thu, 10 Oct 2024 13:31:17 +0100 Subject: [PATCH] Apply crash function to Windows Console --- src/windows/systemw.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/windows/systemw.c b/src/windows/systemw.c index b22b07b5..2d0480c8 100644 --- a/src/windows/systemw.c +++ b/src/windows/systemw.c @@ -230,6 +230,23 @@ void MTY_SetCrashFunc(MTY_CrashFunc func, void *opaque) SYSTEM_OPAQUE = opaque; } +static BOOL WINAPI system_handler_routine(DWORD dwCtrlType) +{ + // Console close == SIGTERM, Ctrl+C == SIGINT + if (SYSTEM_CRASH_FUNC) + SYSTEM_CRASH_FUNC(dwCtrlType == CTRL_CLOSE_EVENT || dwCtrlType == CTRL_C_EVENT, SYSTEM_OPAQUE); + + // Prevent secondary calls to the SYSTEM_CRASH_FUNC + SYSTEM_CRASH_FUNC = NULL; + + // For all except CTRL_LOGOFF_EVENT, exit the process with code 1 + if (dwCtrlType != CTRL_LOGOFF_EVENT) + ExitProcess(1); + + // Prevent additional handlers from running, except for CTRL_LOGOFF_EVENT, which doesn't necessarily mean THIS user is logging off + return dwCtrlType != CTRL_LOGOFF_EVENT; +} + void MTY_OpenConsole(const char *title) { HWND console = GetConsoleWindow(); @@ -262,6 +279,9 @@ void MTY_OpenConsole(const char *title) SetConsoleTitle(titlew); MTY_Free(titlew); + + // Add Ctrl handler + SetConsoleCtrlHandler(system_handler_routine, TRUE); } }