When windows overlap, SDL follows the window stacking order - the topmost window at the mouse position receives the focus. This behavior matches how most operating systems handle window layering.
Here's a demonstration that creates two overlapping windows and reports which one has focus:
#include <SDL.h>
#include <iostream>
#include "Window.h"
class OverlappingWindows {
public:
OverlappingWindows() {
Window1.SDLWindow = SDL_CreateWindow(
"Window 1",
100, 100,// position
400, 300,// size
0
);
Window2.SDLWindow = SDL_CreateWindow(
"Window 2",
300, 200,// overlapping position
400, 300,
0
);
}
void Update() {
SDL_Window* Focused{SDL_GetMouseFocus()};
if (Focused == Window1.SDLWindow) {
std::cout << "Window 1 (Bottom)\n";
} else if (Focused == Window2.SDLWindow) {
std::cout << "Window 2 (Top)\n";
}
Window1.Update();
Window2.Update();
}
private:
Window Window1;
Window Window2;
};
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
OverlappingWindows Windows;
SDL_Event E;
while (true) {
while (SDL_PollEvent(&E)) {
// Handle events...
}
Windows.Update();
}
SDL_Quit();
return 0;
}
Window 2 (Top)
Window 2 (Top)
Window 1 (Bottom)
You can modify which window is on top using SDL_RaiseWindow()
:
// Brings Window1 to front
SDL_RaiseWindow(Window1.SDLWindow);
This is particularly useful when implementing features like:
Remember that window stacking behavior can vary slightly between operating systems, so always test your window management code across different platforms.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to track and respond to mouse focus events in SDL2, including handling multiple windows and customizing focus-related click behavior.