如何通过OpenGL或GLUT检查窗口是否打开?有无类似SFML isOpen的方法?
Great question! Since SFML gives you that handy isOpen() method to check if a window's active, let's walk through how to do the same in raw OpenGL and GLUT—they handle window state a bit differently, but it's totally manageable.
First off, raw OpenGL doesn't include built-in window management—that's handled by platform-specific window systems (like Win32 on Windows, X11 on Linux, or Cocoa on macOS). Because of this, there's no direct equivalent to SFML's isOpen() method. Instead, you have two main options:
Track window state manually: Maintain a boolean variable (e.g.,
bool windowIsOpen = true;) and update it when you receive a window-close event from the underlying system. For example:- On Win32, you'd set
windowIsOpen = false;when handling theWM_CLOSEmessage in your window procedure. - On X11, you'd toggle the variable when you receive a
DestroyNotifyevent.
- On Win32, you'd set
Use platform-specific API calls: You can query the window system directly to check if the window still exists. For example:
- Win32: Use
IsWindow(hwnd)wherehwndis your window handle—this returns a non-zero value if the window is valid. - X11: Call
XQueryWindow(display, window); if it fails (returns 0), the window has been destroyed.
- Win32: Use
Most developers opt for the manual state tracking approach since it's more straightforward and works consistently across your application logic.
GLUT (OpenGL Utility Toolkit) simplifies window management, but it also doesn't have a direct isOpen() function. Instead, you can use a combination of a custom state variable and GLUT's callback system to replicate this behavior:
Here's a quick example of how to implement it:
#include <GL/glut.h> #include <iostream> bool windowIsOpen = true; // Callback triggered when the window is closed void onWindowClose() { windowIsOpen = false; std::cout << "Window closed!" << std::endl; } void renderFrame() { glClear(GL_COLOR_BUFFER_BIT); // Add your rendering logic here glutSwapBuffers(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutCreateWindow("GLUT Window Check"); // Register the close callback glutCloseFunc(onWindowClose); glutDisplayFunc(renderFrame); // Custom main loop to check window state while (windowIsOpen) { glutMainLoopEvent(); // Process pending events renderFrame(); // Trigger rendering } return 0; }
A couple of notes here:
- GLUT's default
glutMainLoop()is blocking, so we useglutMainLoopEvent()instead to process events in our own loop—this lets us check thewindowIsOpenvariable each iteration. - If you need to check for all GLUT windows (not just one), you can use
glutGet(GLUT_WINDOW_NUM_WINDOWS)—if it returns 0, no GLUT windows are open.
内容的提问来源于stack exchange,提问作者ar2015

