How to create a window and renderer with surface and texture using SDL3 in Win32 C++

1 Answer

0 votes
#include <SDL3/SDL.h>

#if _WIN32 // PLATFORM_WINDOWS 

#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR lpCmdLine,
    _In_ int nCmdShow) {
  
    if (!SDL_Init(SDL_INIT_VIDEO)) {
        //SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError());
        MessageBoxA(0, SDL_GetError(), "Couldn't initialize SDL", MB_OK);
        return 3;
    }

    SDL_Window* window;
    SDL_Renderer* renderer;
    if (!SDL_CreateWindowAndRenderer("SDL3 Create Window And Renderer with surface and texture", 640, 480, SDL_WINDOW_RESIZABLE, &window, &renderer)) {
        //SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window and renderer: %s", SDL_GetError());
        MessageBoxA(0, SDL_GetError(), "Couldn't create window and renderer", MB_OK);
        return 3;
    }

    SDL_Surface* surface = SDL_LoadBMP("abc.bmp");
    if (!surface) {
        //SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create surface from image: %s", SDL_GetError());
        MessageBoxA(0, SDL_GetError(), "Couldn't create a surface from image", MB_OK);
        return 3;
    }
    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
    if (!texture) {
        //SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture from surface: %s", SDL_GetError());
        MessageBoxA(0, SDL_GetError(), "Couldn't create texture from surface", MB_OK);
        return 3;
    }

    SDL_DestroySurface(surface);

    SDL_Event event;

    while (1) {
        SDL_PollEvent(&event);
        if (event.type == SDL_EVENT_QUIT) {
            break;
        }
        SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
        SDL_RenderClear(renderer);
        SDL_RenderTexture(renderer, texture, NULL, NULL);
        SDL_RenderPresent(renderer);
    }

    SDL_DestroyTexture(texture);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    SDL_Quit();

    return 0;
}

#endif

 



answered Dec 28, 2024 by avibootz
edited Jan 1, 2025 by avibootz
...