Creating an overlay window in SDL that always stays on top of other SDL windows involves a combination of SDL window flags and platform-specific techniques.
SDL itself doesn't directly support "always on top" windows, but you can achieve this effect with a few tricks.
First, create the window with the appropriate SDL flags. Typically, you would want the window to be borderless to give it an overlay-like appearance:
#include <SDL.h>
class OverlayWindow {
public:
OverlayWindow() {
SDLWindow = SDL_CreateWindow(
"Overlay Window",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
400, 300,
SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALWAYS_ON_TOP
);
}
~OverlayWindow() {
SDL_DestroyWindow(SDLWindow);
}
SDL_Window* SDLWindow{nullptr};
};
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
OverlayWindow overlay;
SDL_Event Event;
while (true) {
while (SDL_PollEvent(&Event)) {
if (Event.type == SDL_QUIT) {
return 0;
}
}
}
SDL_Quit();
return 0;
}
To make the window stay on top, you might need to use platform-specific APIs. Here's how you can achieve this on Windows using the Win32Â API:
#include <SDL.h>
#include <SDL_syswm.h>
#include <windows.h>
class OverlayWindow {
public:
OverlayWindow() {
SDLWindow = SDL_CreateWindow(
"Overlay Window",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
400, 300,
SDL_WINDOW_BORDERLESS
);
HWND hwnd = GetSDLWindowHandle(SDLWindow);
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE);
}
~OverlayWindow() {
SDL_DestroyWindow(SDLWindow);
}
SDL_Window* SDLWindow{nullptr};
private:
HWND GetSDLWindowHandle(SDL_Window* window) {
SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version);
SDL_GetWindowWMInfo(window, &wmInfo);
return wmInfo.info.win.window;
}
};
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
OverlayWindow overlay;
SDL_Event Event;
while (true) {
while (SDL_PollEvent(&Event)) {
if (Event.type == SDL_QUIT) {
return 0;
}
}
}
SDL_Quit();
return 0;
}
In this example, SetWindowPos()
is used to set the window as always on top (HWND_TOPMOST
).
Creating an overlay window in SDL involves combining SDL's window creation functions with platform-specific code to achieve the desired always-on-top behavior.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to manage and control window input focus in SDL applications, including how to create, detect, and manipulate window focus states.