简体   繁体   English

C++:程序终止时执行函数

[英]C++: Execute function when program terminates

Some programs pop "Save before exit?"一些程序弹出“退出前保存?” message when terminating.终止时的消息。 And I wonder if I can implement this with C++ console application.我想知道我是否可以用 C++ 控制台应用程序实现这个。 So I tried some standard functions like signal and atexit .所以我尝试了一些标准函数,比如signalatexit

But they only work when:但它们仅在以下情况下有效:

  • main() returns ( atexit ) main()返回 ( atexit )
  • sending interrupt through Ctrl+C (on Windows, SIGINT )通过 Ctrl+C 发送中断(在 Windows 上, SIGINT
  • an error occurs ( SIGABRT )发生错误( SIGABRT

So yeah, how?所以是的,如何? Is it only possible with GUI application?是否只能使用 GUI 应用程序?

In comments, you said:在评论中,你说:

I want exit events to happen when that 'X' button is pressed(On windows).我希望在按下“X”按钮时发生退出事件(在 Windows 上)。 That's part of GUI I guess.我猜那是 GUI 的一部分。 Than what kind of request is sent to program when the exit button of the console is pressed?当按下控制台的退出按钮时,会向程序发送什么样的请求?

You can use SetConsoleCtrlHandler() to register auser defined callback function that receives a CTRL_CLOSE_EVENT notification when the console window is closed:您可以使用SetConsoleCtrlHandler()注册用户定义的回调函数,该函数在控制台窗口关闭时接收CTRL_CLOSE_EVENT通知:

A signal that the system sends to all processes attached to a console when the user closes the console (either by clicking Close on the console window's window menu, or by clicking the End Task button command from Task Manager).当用户关闭控制台(通过单击控制台窗口的窗口菜单上的关闭,或单击任务管理器中的结束任务按钮命令)时,系统发送到所有连接到控制台的进程的信号。

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

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