Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My consoleHandler does not handle CTRL+C even though properly set

Tags:

c++

window

winapi

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;
}
like image 629
metablaster Avatar asked Apr 12 '26 06:04

metablaster


1 Answers

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?

like image 130
Torben Schramme Avatar answered Apr 14 '26 21:04

Torben Schramme



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!