Gold mine of Visual C++ tricks!
Posts tagged Console control handler
How to handle Ctrl+C in Console Applications?
01477 days
![]()
Some of our testapps or applications are console applications and testers usually crash those by applying Ctrl+C. This is because Console will forcefully terminate the application if it receives a Ctrl+C. For those situation, you can handle the Ctrl+C yourself and can do graceful exit.
![]()
You can use the function – SetConsoleCtrlHandler() to register a callback function to handle Ctrl+C events from the console. See the following code snippet.
BOOL CtrlHandler(DWORD dwCtrlType)
{
if( CTRL_C_EVENT == dwCtrlType)
{
// Recd Ctrl+C. Write your clean up code here.
}
}
void main()
{
SetConsoleCtrlHandler(
(PHANDLER_ROUTINE) CtrlHandler, // handler function
TRUE); // add to list
}
![]()
Together with Ctrl+C you can handle more console events. See the list.
- CTRL_CLOSE_EVENT
- CTRL_LOGOFF_EVENT
- CTRL_SHUTDOWN_EVENT
- CTRL_BREAK_EVENT
![]()
Targeted Audience – Intermediate.