SetConsoleCtrlHandler常规问题 [英] SetConsoleCtrlHandler routine issue
问题描述
我在C ++中编写一个控制台应用程序。
我使用SetConsoleCtrlHandler来捕获关闭和CTRL + C按钮。这允许我的所有线程正确停止和退出。
其中一个线程执行一些保存,需要一些时间来完成,我有一些代码在控制台crtl句柄例程。 MSDN指定一个框应该在CTRL_CLOSE_EVENT 5秒后弹出,而是我的进程退出。
这是烦人的调试控制台应用程序也过程退出之前,你可以步骤,我不知道可能是什么问题(我有Windows 7 64位)。
另外,奇怪的是,如果我的例程返回TRUE动作),它仍然关闭应用程序。例程被调用,因此SetConsoleCtrlHandler已成功安装。
例如:
BOOL WINAPI ConsoleHandlerRoutine(DWORD dwCtrlType)
{
if(dwCtrlType == CTRL_CLOSE_EVENT)
{
return TRUE;
}
return FALSE;
}
int _tmain(int argc,_TCHAR * argv [])
{
BOOL ret = SetConsoleCtrlHandler(ConsoleHandlerRoutine,TRUE);
while(true)
{
Sleep(1000);
}
return 0;
}
任何想法?
看起来你不能再忽略Windows 7上的关闭请求。
得到CTRL_CLOSE_EVENT事件,从那一刻起,你会得到10秒,做任何你需要做的事情,然后它自动关闭。所以你可以在处理程序中做任何你需要做的工作,或者设置一个全局标志。
case CTRL_CLOSE_EVENT:// CTRL -CLOSE:确认用户要退出。
close_flag = 1;
while(close_flag!= 2)
Sleep(100);
return TRUE;有趣的是:当CTRL_CLOSE_EVENT事件中的代码运行时,主程序继续运行。所以你可以检查标志,并在某处做一个'close_flag = 2;'。但记住,你只有10秒。 (所以记住,你不想挂起你的主程序流等待键盘输入例如。)
I'm writting a console application in C++.
I use SetConsoleCtrlHandler to trap close and CTRL+C button. This allows for all my threads to stop and exit properly.
One of the thread performs some saving that require some time to complete and I have some code to wait in the console crtl handle routine. MSDN specify that a box should pop up after 5 seconds for CTRL_CLOSE_EVENT, but instead my process exits.
This is annoying for debugging console application too as the process exits before you can step through and I don't know what may be the problem (I have Windows 7 64bits).
Also, strangely if my routine returns TRUE (to simply disable the close action), it still closes the application. The routine does get called, so the SetConsoleCtrlHandler was successful installed.
e.g.:
BOOL WINAPI ConsoleHandlerRoutine(DWORD dwCtrlType)
{
if (dwCtrlType == CTRL_CLOSE_EVENT)
{
return TRUE;
}
return FALSE;
}
int _tmain(int argc, _TCHAR* argv[])
{
BOOL ret = SetConsoleCtrlHandler(ConsoleHandlerRoutine, TRUE);
while (true)
{
Sleep(1000);
}
return 0;
}
Any ideas?
解决方案 It looks like you can no longer ignore close requests on Windows 7.
You do get the CTRL_CLOSE_EVENT event though, and from that moment on, you get 10 seconds to do whatever you need to do before it auto-closes. So you can either do whatever work you need to do in the handler or set a global flag.
case CTRL_CLOSE_EVENT: // CTRL-CLOSE: confirm that the user wants to exit.
close_flag = 1;
while(close_flag != 2)
Sleep(100);
return TRUE;
Fun fact: While the code in your CTRL_CLOSE_EVENT event runs, the main program keeps on running. So you'll be able to check for the flag and do a 'close_flag = 2;' somewhere. But remember, you only have 10 seconds. (So keep in mind you don't want to hang up your main program flow waiting on keyboard input for example.)
这篇关于SetConsoleCtrlHandler常规问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!