简体   繁体   English

单击关闭控制台窗口以结束c ++控制台程序是正确的方法吗?

[英]click close console window to end a c++ console program is proper way?

I have just got this problem for a few days. 我刚遇到这个问题几天。 Before, I've always thought that letting the program exit by returning from main and clicking close the console window is the same way to end the program. 以前,我一直认为通过从main返回并单击关闭控制台窗口来退出程序与结束程序的方法相同。

However, I've found that they are different. 但是,我发现它们是不同的。 Since my program opens a camera which is an object. 由于我的程序打开了一个相机,这是一个对象。 And closing the console windows does not destroy or clean up the object. 关闭控制台窗口不会破坏或清理对象。 So the next time I have error to open the camera again 所以下次我再次打开相机时出错

I just need a confirm if this is true? 我只需要确认这是否正确?

Then why only until now I can see the problem? 那为什么直到现在我仍然可以看到问题?

Closing a running console application will kill the process, not giving you the chance for any clean up code. 关闭正在运行的控制台应用程序将终止该过程,不会给您提供任何清理代码的机会。 I guess you could hook a windows message loop to trap the WM_CLOSE message and do proper cleanup, but at the end of the day, you just shouldn't kill the process. 我猜您可能会钩住Windows消息循环以捕获WM_CLOSE消息并进行适当的清理,但是到最后,您不应该终止该过程。

Closing a console window in Windows, kills the running program (or stack of running programs). 在Windows中关闭控制台窗口会杀死正在运行的程序(或正在运行的程序堆栈)。 Unless it has registered a handler for this event, it gets no chance to clean up. 除非它已为此事件注册处理程序,否则它没有机会进行清理。 If you want solution, register a handler. 如果需要解决方案,请注册一个处理程序。

Hm, consulting the documentation, wait a few secs… 嗯,正在查阅文档,请等待几秒钟……

OK, look up SetConsoleCtrlHandler . OK,查找SetConsoleCtrlHandler

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM