glfwPollEvents automatically set the close flag which causes GLFW to close the window

Does anyone know under what circumstances will glfwPollEvents() automatically set the close flag that causes GLFW to close the window?

For learning purpose, currently my program contains both DirectX11’s code (using Win32 API directly) and OpenGL’s code (using GLFW). The window creation and main loop for each API are in separate functions. When you select another API from the UI inside the program, it will cause the function to return to the main function, which will destroy the current window and release all resource (since they are local variables), and call another function to create a new window and a main loop. Switching from GLFW to Win32 has no problem at all, but when switching from Win32 to GLFW, despite that GLFW window can be created without any problem and error, the main loop will execute only once, then it will automatically close afterwards. Both glError() and glfwGetError() return no errors at all.

After debugging I found that glfwPollEvents() somehow sets the close flag, which causes glfwWindowShouldClose() to return true and end the main loop. If I comment out glfwPollEvents(), OpenGL will render without any problem, but of course there won’t be any event polling. I tried setting up WindowCloseCallback, and right after the program executes glfwPollEvents(), the callback is called, so clearly either glfwPollEvents() sets the close flag, or the flag is set elsewhere. The problem is KeyCallback is never called and I didn’t call glfwSetWindowShouldClose() anywhere in the code, so I don’t know why the close flag is set.

Does anyone know why this happened? Thanks.

Hi @deadshot465 welcome to the GLFW forums!

The Windows implementation of GLFW sets the window close flag if WM_QUIT is sent to the application or WM_CLOSE is sent to a window are received. I suspect one of these is still in the message queue after you destroy the first window, and thus glfwPollEvents() picks this up and closes the window.

Since WM_CLOSE is sent to a particular window handle, I’d guess that the message you’re getting is WM_QUIT. If you’re able to set breakpoints in the code of the _glfwInputWindowCloseRequest function you should be able to see what’s causing it to close.

If this is indeed the problem, clearing out the message queue completely prior to opening the new window might help.

2 Likes

Thank you for the insight!
Indeed, it was the WM_QUIT message that was still lingering in the queue. After I used PeekMessage() to ensure that WM_QUIT was removed before creating another window, everything worked.

Thank you again for the help :slight_smile: