Reputation: 2184
Related question is here
but it does not work for me, when I press CTRL + C debugger issues "unhandled event", only closing the console works fine but not for CTRL + C, what is wrong with my code?
Here is the code:
#include <windows.h>
#include <iostream>
BOOL WINAPI consoleHandler(DWORD signal) noexcept
{
switch (signal)
{
case CTRL_C_EVENT:
ExitProcess(0); // not working
case CTRL_BREAK_EVENT:
break;
case CTRL_CLOSE_EVENT:
ExitProcess(0); // this works
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
break;
}
return TRUE;
}
int main()
{
if (!SetConsoleCtrlHandler(consoleHandler, TRUE))
{
std::cout << "ERROR: Could not set control handler" << std::endl;
return EXIT_FAILURE;
}
DoSomeWork();
std::cin.get();
return 0;
}
Upvotes: 2
Views: 1559
Reputation: 2140
From MSDN:
CTRL+BREAK is always treated as a signal, but typical CTRL+C behavior can be changed in three ways that prevent the handler functions from being called:
- The SetConsoleMode function can disable the ENABLE_PROCESSED_INPUT mode for a console's input buffer, so CTRL+C is reported as keyboard input rather than as a signal.
- Calling SetConsoleCtrlHandler with the NULL and TRUE arguments causes the calling process to ignore CTRL+C signals. This attribute is inherited by child processes, but it can be enabled or disabled by any process without affecting existing processes.
- If a console process is being debugged and CTRL+C signals have not been disabled, the system generates a DBG_CONTROL_C exception. This exception is raised only for the benefit of the debugger, and an application should never use an exception handler to deal with it. If the debugger handles the exception, an application will not notice the CTRL+C, with one exception: alertable waits will terminate. If the debugger passes the exception on unhandled, CTRL+C is passed to the console process and treated as a signal, as previously discussed.
Perhaps the third point applies to your problem? Does your application behaves as expected when running in Release mode?
Upvotes: 3