我开始在C中进行SDL编程。这个简单的程序循环通过彩虹色并用它们填充窗口。 (如果有帮助的话,这是在Debian和Gnome上进行的。)
由于某些原因,如果我点击关闭窗口,程序永远不会注册退出信号。如何修复循环结构以使程序正常退出?
#include <SDL2/SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(void)
{
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Event event;
bool quit = false;
int i;
int rgb_rainbow[6][3] = { {255, 0, 0},
{255, 127, 0},
{255, 255, 0},
{0, 255, 0},
{0, 0, 255},
{75, 0, 130} };
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Couldn't initialize SDL: %s", SDL_GetError());
return(3);
}
if (SDL_CreateWindowAndRenderer(640,640,
SDL_WINDOW_RESIZABLE, &window, &renderer)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Couldn't create window and renderer: %s", SDL_GetError());
return(3);
}
while (quit == false) {
for (i = 0; i < 6; ++i ) {
SDL_PollEvent(&event);
if (event.type == SDL_QUIT) {
quit = true;
break;
}
SDL_SetRenderDrawColor(renderer,
rgb_rainbow[i][0],
rgb_rainbow[i][1],
rgb_rainbow[i][2], 255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
SDL_Delay(500);
}
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return(0);
}
答案 0 :(得分:2)
关闭窗口事件为SDL_WINDOWEVENT
,window.event
设置为SDL_WINDOWEVENT_CLOSE
。您还只获得一个事件前端队列,甚至没有检查队列是否有一个。看看这个:
while (quit == false) {
for (i = 0; i < 6; ++i ) {
while(SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT ||
(event.type == SDL_WINDOWEVENT &&
event.window.event == SDL_WINDOWEVENT_CLOSE)) {
quit = true;
}
}
if(quit) { break; }
SDL_SetRenderDrawColor(renderer,
rgb_rainbow[i][0],
rgb_rainbow[i][1],
rgb_rainbow[i][2], 255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
SDL_Delay(500);
}
}
通常优良做法是让主循环只渲染一帧而不是6(或任何其他数字)。