0

So I have developed a C++ console application in Visual Studio to keep log of attendance with a credit card reader, then spit out a .csv file. However, as the program is right now, the user has to manually type "exit" for the program to close successfully and generate the .csv.

I know that non-tech people wouldn't realize this and could just hit the X button and lose their data. Is there any way to catch the signal and allow the program to do its cleanup work and close?

The program is already Windows-only so that is not an issue.

1 Answers1

1

Use SetConsoleCtrlHandler to set-up a callback for the CTRL_CLOSE_EVENT event which is raised when the Window caption close "X" button is pressed.

Note that the Ctrl+C event is different: that's CTRL_C_EVENT, but you handle it the same way: Handle CTRL+C on Win32

#include <Windows.h>

BOOL onConsoleEvent(DWORD event) {

    switch( event ) {
        case CTRL_C_EVENT:
        case CTRL_CLOSE_EVENT:
            // do stuff
            break;
    }

    return TRUE;
}

int main(int argc, char* argv[]) {

    if( !SetConsoleCtrlHandler( onConsoleEvent, TRUE ) ) {
        // die
    }

    // do stuff
}

This is Windows-specific, as you say., which shouldn't be a problem.

Note that you can use the portable signal function to set-up a handler for the SIGINT event (which corresponds to Ctrl+C) however, to my knowledge, Windows' signal function does not have a callback event that corresponds to the X button, so for that you have to use SetConsoleCtrlHandler.

#include <signal.h> // use `<cstdlib>` in C++

void onSigint(int value) {
    // do stuff
}

int main(int argc, char* argv[]) {

    signal(SIGINT, onSigint);

    // do stuff
}
Community
  • 1
  • 1
Dai
  • 141,631
  • 28
  • 261
  • 374
  • I'm familiar with things like SIGINT and other termination signals. Is this similar? –  Nov 11 '16 at 00:26
  • @Koronakesh yes, they're conceptually the same, except `SetConsoleCtrlHandler` offers more functionality and is platform-specific. – Dai Nov 11 '16 at 00:32