SDL窗口出现后崩溃?

问题描述 投票:0回答:1

我的 SDL 窗口没有保持打开状态:它几乎在打开时立即关闭,而 Visual Studio 调试控制台保持打开状态:

#include <iostream>
#include "SDL.h"
#include "SDL_image.h"
#include <cstdio>

using namespace std;

int main(int argc, char* argv[])
{
    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_Window* window = SDL_CreateWindow("SDLwindow", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);

    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);

    SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);

    SDL_RenderClear(renderer);

    SDL_RenderPresent(renderer);

    SDL_Delay(3000);

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
   
    return 0;
}

我尝试增加延迟,但除此之外我不确定我要解决什么问题。

c++ window sdl-2
1个回答
0
投票

3秒延迟后,程序进行到以下几行:

SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();

return 0;

关闭窗口并终止程序。要保持窗口打开直到用户手动关闭它,您需要添加一个循环来处理事件并保持应用程序运行:

#include <SDL.h>

#ifdef main
#undef main
#endif

int main()
{
    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_Window* window = SDL_CreateWindow("SDLwindow", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);

    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);

    SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);

    SDL_RenderClear(renderer);

    SDL_RenderPresent(renderer);

    // Event loop
    SDL_Event event;
    bool quit = false;
    while (!quit)
    {
        while (SDL_PollEvent(&event) != 0)
        {
            if (event.type == SDL_QUIT)
            {
                quit = true;
            }
        }
    }
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.