11

我真的很难用 FreeGLUT 关闭我的控制台应用程序。

我想知道最好的方法是采取一切可能的关闭方式,因为我不想要任何内存泄漏(我很害怕那些)。

所以我已经尝试了以下方法,这给了我这样的例外:

myProject.exe 中 0x754e6a6f 处的第一次机会异常:0x40010005:Control-C。

int main(int argc, char **argv)
{
    if( SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, true) )
    {
        // more code here as well ....


        glutCloseFunc(close); // set the window closing function of opengl
        glutMainLoop();
        close(); // close function if coming here somehow
    }
    else
    {
        return 1;
    }
    return 0;
}

void close()
{
    // keyboardManager is a pointer to a class
    // which I want to delete, so no memory will leak.
    if(keyboardManager) // do I need this check?
        delete keyboardManager;
}

bool CtrlHandler(DWORD fdwCtrlType)
{
    switch(fdwCtrlType)
    {
        // Handle the CTRL-C signal.
        case CTRL_C_EVENT:
        // and the close button
        case CTRL_CLOSE_EVENT:
          close();
          return true;

        // Pass other signals to the next handler. 
        case CTRL_BREAK_EVENT:
            return false;

    // delete the pointer anyway
        case CTRL_LOGOFF_EVENT:
        case CTRL_SHUTDOWN_EVENT:
        default:
            close();
            return false; 
    } 
}

所以正确的是:

  1. 关闭过剩之窗
  2. 关闭控制台应用程序x
  3. 用我的键盘管理器关闭我的过剩窗口if(keyboardManager->isKeyDown[27]) glutExit();

出问题的是:

  1. 使用 CTRL+C 关闭控制台应用程序,它会从上面给出异常。

这是在 Visual Studio 2008 C++ 中。

更新

我发现抛出了异常,因为我在调试。所以这不会是一个问题。但问题仍然悬而未决:真正关闭过剩的最优雅方式是什么?

atexit()似乎也可以,所以也许我可以使用它?

4

4 回答 4

16

我使用这个功能:

void glutLeaveMainLoop ( void ); 

他们的 sourceforge 页面上有更多信息,但我从未使用过该功能:

glutLeaveMainLoop 函数使 freeglut 停止事件循环。如果 GLUT_ACTION_ON_WINDOW_CLOSE 选项已设置为 GLUT_ACTION_CONTINUE_EXECUTION,控制将返回调用 glutMainLoop 的函数;否则应用程序将退出。

http://freeglut.sourceforge.net/docs/api.php#EventProcessing

在空指针上使用是安全delete的,无需检查。

于 2011-02-21T00:51:45.983 回答
5

感谢 Maarten 的帖子,这对我有用:

glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,GLUT_ACTION_CONTINUE_EXECUTION);

每当您想离开主循环而不终止应用程序时,请使用:

glutLeaveMainLoop();

不要忘记包含“freeglut.h”

于 2016-09-29T14:18:30.737 回答
1

我用glutDestroyWindow(int handle);

或者

根据 ID: OpenGL 论坛上的 RigidBody

void destroy_window() 
{
 window_valid = -1;
}

void display_func() 
{
 if(window_valid == -1)
   return;
 // draw things
}
于 2016-07-06T00:06:43.830 回答
0

试试这个方法:

glutDestroyWindow(glutGetWindow());
于 2018-10-01T08:21:23.433 回答