17.3.19 Control Handlers

SetConsoleCtrlHandler allows you to create and register one or more functions to handle Ctrl-C and Ctrl-break for the calling process. It may also be used to remove a handler from the list of handlers registered for a process. The handler functions will always be invoked if Ctrl-break is input; but Ctrl-C is only passed through if the console is in processed input mode.

The handler function takes a single argument that will identify which control character was input. The function returns a Boolean result. If TRUE, it indicates that the control character was handled and other handlers should not be invoked. If no handlers are registered for this application, a default handler that calls ExitProcess is called. If multiple handlers have been registered, they are called on a last registered, first called basis. If none of the handlers returns TRUE, the default handler is called.

// control handler that handles Ctrl-C, passes Ctrl-break

BOOL CtrlHandler(ULONG CtrlType) {

switch (CtrlType) {

CTRL_C_EVENT:

// handle Ctrl-C

return TRUE;

CTRL_BREAK_EVENT:

default:

return FALSE;

}

}

.

.

.

BOOL bResult;

// add the handler to the list for this process

bResult = SetConsoleCtrlHandler(

(PHANDLER_ROUTINE) &CtrlHandler, TRUE);