Registering a Control Handler Function Example
This is an example of the SetConsoleCtrlHandler() function that is used to install a control handler. When a CTRL+C signal is received, the control handler returns TRUE, indicating that it has handled the signal. Doing this prevents other control handlers from being called. When a CTRL_CLOSE_EVENT signal is received, the control handler returns TRUE, causing the system to display a dialog box that gives the user the choice of terminating the process and closing the console or allowing the process to continue execution. If the user chooses not to terminate the process, the system closes the console when the process finally terminates. When a CTRL+BREAK, CTRL_LOGOFF_EVENT, or CTRL_SHUTDOWN_EVENT signal is received, the control handler returns FALSE. Doing this causes the signal to be passed to the next control handler function. If no other control handlers have been registered or none of the registered handlers returns TRUE, the default handler will be used, resulting in the process being terminated.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
BOOL CtrlHandler(DWORD fdwCtrlType)
// Note: Console functions, or any C run-time functions that
// call console functions, may not work reliably during processing
// of any of the three signals mentioned previously.
// The reason is that some or all of the internal console cleanup
// routines may have been called before executing the process signal handler.
// Handle the CTRL-C signal.
// CTRL-CLOSE: confirm that the user wants to exit
// Pass other signals to the next handler
int wmain(int argc, WCHAR **argv)
if(SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE))
wprintf(L"\nThe Control Handler is installed.\n" );
wprintf(L"\n -- Now try pressing Ctrl+C or Ctrl+Break, or" );
wprintf(L"\n try logging off or closing the console...\n" );
wprintf(L"\n(...waiting in a loop for events...)\n\n" );
// While true
wprintf(L"\nERROR: Could not set control handler");
Build and run the project. The following screenshot is a sample output.