Window Visibility

Toggle always-on-top with a key

How can I toggle the always-on-top behavior with a key press?

Abstract art representing computer programming

You can toggle the "always-on-top" behavior of a window by modifying its flags in response to a key press. SDL2 provides the SDL_SetWindowAlwaysOnTop() function, which allows you to enable or disable this feature dynamically.

By tracking the current state with a boolean, you can easily flip this behavior when a specific key is pressed. Here’s an example program:

#include <SDL.h>
#include <iostream>

int main() {
  if (SDL_Init(SDL_INIT_VIDEO) != 0) {
    std::cout << "SDL_Init Error: "
      << SDL_GetError() << '\n';
    return 1;
  }

  SDL_Window* window =
    SDL_CreateWindow("Always on Top Toggle",
                     SDL_WINDOWPOS_CENTERED,
                     SDL_WINDOWPOS_CENTERED,
                     640, 480,
                     SDL_WINDOW_SHOWN);
  if (!window) {
    std::cout << "SDL_CreateWindow Error: "
      << SDL_GetError() << '\n';
    SDL_Quit();
    return 1;
  }

  bool running = true;
  bool alwaysOnTop = false; 
  SDL_Event event;

  while (running) {
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) {
        running = false;
      } else if (event.type == SDL_KEYDOWN) {
        if (event.key.keysym.sym == SDLK_t) { 
          alwaysOnTop = !alwaysOnTop; 
          SDL_SetWindowAlwaysOnTop(    
            window, alwaysOnTop); 
          std::cout << "Always on top: "
            << (alwaysOnTop
                  ? "Enabled"
                  : "Disabled") << '\n';
        }
      }
    }
  }

  SDL_DestroyWindow(window);
  SDL_Quit();
  return 0;
}
Pressing 'T' toggles the always-on-top behavior.

Notes

  • The toggle key (e.g., T in this example) can be changed to suit your program.
  • This behavior is particularly useful for debugging tools or applications that require high visibility in multitasking environments.
  • Be aware that enabling always-on-top might interfere with user workflows, so use it judiciously.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 62 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved