即使设置正确,我的 consoleHandler 也无法处理 CTRL+C

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

相关问题是here

但它对我不起作用,当我按下 CTRL + C 时,调试器出现问题 "unhandled event",仅关闭控制台可以正常工作,但对于 CTRL + C 则不行,我的代码有什么问题?

代码如下:

#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;
}

来自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.

也许第三点适用于您的问题?当 运行 处于发布模式时,您的应用程序是否按预期运行?