gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:03 29 4
gpt4 key购买 nike

相关问题是here

但它对我不起作用,当我按 CTRL + C 调试器发出“未处理的事件”时,仅关闭控制台工作正常但 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.

也许第三点适用于您的问题?在 Release模式下运行时,您的应用程序是否按预期运行?

关于c++ - 即使设置正确,我的 consoleHandler 也无法处理 CTRL+C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58149953/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com