Fullscreen mode with mouse position restriction and display centering

Hello all,

I am trying to make a program which would work only for a specific screen resolution (for instance 1280x720). I want it to be centered on the screen when running in fullscreen mode, surrounded with black bars on the 4 sides to compensate.
When switching to fullscreen mode with SDL_SetWindowFullscreen, it works well if the screen is able to display the resolution natively. But if the screen doesn’t support that resolution natively then I don’t get letterboxing. For instance if the screen switch to fullscreen 1280x1024, then the image is not centered (but instead it’s at the top left corner) and the mouse can move outside the drawed area (it seems it can move on the whole screen logical area, 1280x1024 in this case).

So I have implement the centering and mouse restriction myself and it seems to works. I would be happy if some people were able to tell me if this is how it should be done in SDL2 or if there is another and more recommended method to do it?


#include <SDL.h>
#include <stdbool.h>
#include <stdio.h>

int main(void) {
  int w = 1280, h = 720;
  SDL_Window *window = SDL_CreateWindow("SDL", 0, 0, w, h, SDL_WINDOW_SHOWN);
  SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
  SDL_Rect view_rect = {0, 0, w, h};
  SDL_SetWindowMouseRect(window, &view_rect);

  bool is_fullscreen = false;
  bool quit_requested = false;
  while (!quit_requested) {
    SDL_Event e;
    int mouse_x, mouse_y;
    SDL_GetMouseState(&mouse_x, &mouse_y);
    printf("Mouse at %d %d\n", mouse_x - view_rect.x, mouse_y - view_rect.y);
    while (SDL_PollEvent(&e) != 0) {
      if (e.type == SDL_QUIT) {
        quit_requested = true;
      } else if (e.type == SDL_KEYUP) {
        if (e.key.keysym.scancode == SDL_SCANCODE_F12) {
          if (is_fullscreen) {
            SDL_SetWindowFullscreen(window, 0);
            is_fullscreen = false;
          } else {
            SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN);
            is_fullscreen = true;
            SDL_DisplayMode mode;
            SDL_GetWindowDisplayMode(window, &mode);
            view_rect.x = ceil(mode.w - w) / 2;
            view_rect.y = ceil(mode.h - h) / 2;
            SDL_RenderSetViewport(renderer, &view_rect);
            SDL_SetWindowMouseRect(window, &view_rect);
            printf("Display mode: %dx%d\n", mode.w, mode.h);
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);

    SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
    SDL_RenderFillRect(renderer, &(SDL_Rect){0,0,w,h});

    SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
    SDL_RenderFillRect(renderer, &(SDL_Rect){0, 0, 10, 10});
    SDL_RenderFillRect(renderer, &(SDL_Rect){0, h-10, 10, 10});

  return 0;