I'm trying to use SDL2 to take a screenshot of the entire desktop in windows. However, when looking at the resulting .bmp
file it's completely black. Any help would be appreciated.
Here's my code:
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window* window = SDL_CreateWindowFrom(GetDesktopWindow());
int w, h;
SDL_GetWindowSize(window, &w, &h);
uint32_t wnd_pix_fmt = SDL_GetWindowPixelFormat(window);
if(wnd_pix_fmt == SDL_PIXELFORMAT_UNKNOWN)
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Window pix fmt error", SDL_GetError(), NULL);
SDL_Surface* screenshot = SDL_CreateRGBSurfaceWithFormat(0, w, h, 32, wnd_pix_fmt);
if(!screenshot)
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "RGB surface error", SDL_GetError(), NULL);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
if(!renderer)
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Renderer error", SDL_GetError(), NULL);
if(SDL_RenderReadPixels(renderer, &screenshot->clip_rect, screenshot->format, screenshot->pixels, screenshot->pitch))
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "RendererReadPixels error", SDL_GetError(), NULL);
SDL_SaveBMP(screenshot, "screenshot.bmp");
SDL_FreeSurface(screenshot);
NOTE: Even when I set SDL_Window* window
to a window created with SDL_CreateWindow
it's still completely black. On a different forum, they mentioned this may have to do with a double buffering issue. I'm unaware of how to solve such an issue though.