Console Signals Handler


Click here to change the theme.

The following is an example of setting a handler for console signals.

#define STRICT 1
#include <windows.h>
#include <ctime>
#include <iostream>
using namespace std;

bool GlobalQuit = false;

BOOL WINAPI CtrlHandler(DWORD fdwCtrlType) {
switch (fdwCtrlType) {
    case CTRL_C_EVENT:
        Beep(1000, 1000);
    case CTRL_CLOSE_EVENT:
    case CTRL_BREAK_EVENT:
    case CTRL_LOGOFF_EVENT:
    case CTRL_SHUTDOWN_EVENT:
        cout << "Signal to quit was received\n";
        GlobalQuit = true;
        return TRUE;
    default:
        return FALSE;
    }
}

int main(int argc, char *argv[], char *envp[]) {
    struct tm *today;
    time_t ltime;
    char *p;
SetConsoleCtrlHandler(CtrlHandler, TRUE);
while (!GlobalQuit) {
    time(&ltime);
    today = localtime(&ltime);
    p = asctime(today);
    Sleep(2000);
    }
return 0;
}

Use GenerateConsoleCtrlEvent to generate a CTRL+C or a CTRL+BREAK signal.