Mouse Focus with Overlapping Windows
When using SDL_GetMouseFocus()
, what happens if the mouse is over where two windows overlap?
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:
- Dialog boxes that need to stay above the main window
- Tool windows that should float above your application
- Picture-in-picture views where one window should always be visible
Remember that window stacking behavior can vary slightly between operating systems, so always test your window management code across different platforms.
Managing Mouse Focus with SDL2
Learn how to track and respond to mouse focus events in SDL2, including handling multiple windows and customizing focus-related click behavior.