【问题标题】:How to capture application close event for c++ command line project?如何捕获 C++ 命令行项目的应用程序关闭事件?
【发布时间】:2015-02-07 04:30:36
【问题描述】:

我正在 Visual Studio 中开发 c++ 命令行项目。 我需要捕获应用程序关闭事件(在运行应用程序时使用 CTRL+Z 关闭应用程序或关闭命令行窗口)。

我的应用看起来像:

  int main()
    {
       //crete app object, will open some files and run the code.
       myApp app;
       app.run();

       getchar();
    }

如果我如上所述明确关闭应用程序,myApp 析构函数将不会执行。所以我需要一些方法来在我的应用程序中捕获这个关闭事件(如 Qt 中的 QObject::closeEvent())。

提前致谢。

【问题讨论】:

  • 好像在windows上扔了一个CTRL_CLOSE_EVENThere可能对你有帮助。
  • Ctrl+Z 只是意味着结束 STDIN 并关闭句柄。之后它的作用完全是特定于应用程序的。要关闭命令窗口,请参阅@JeffreyBencteux 发布的链接。
  • atexit function 指定程序正常终止时不带参数自动调用的函数。

标签: c++ visual-studio-2010 qt command-line command-prompt


【解决方案1】:

在通常情况下,main() 中创建的对象不会导致析构函数。但是有一个很好且优雅的解决方案——你可以把你的代码放在额外的括号中,然后析构函数就会被调用:

int main()
{
    {        
        myApp app;
        app.run();

        getchar();
    } // At this point, the object's destructor is invoked
}

【讨论】:

    猜你喜欢
    • 2016-03-12
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    相关资源
    最近更新 更多