Window Edge Snapping
How can I make my window snap to the edges of the screen like in Windows?
Edge snapping (sometimes called "aero snap") is a popular window management feature that we can implement using SDL. Here's how to create basic edge snapping functionality:
Basic Edge Detection
First, we need to detect when a window is near a screen edge:
#include <SDL.h>
#include <cmath> // for std::abs
bool IsNearEdge(
int Position, int Edge, int SnapDistance = 20
) {
return std::abs(Position - Edge) < SnapDistance;
}
void HandleWindowMove(SDL_Window* Window) {
// Get current window position
int WinX, WinY;
SDL_GetWindowPosition(Window, &WinX, &WinY);
// Get screen dimensions
SDL_DisplayMode Display;
SDL_GetCurrentDisplayMode(0, &Display);
// Check if near any edge
if (IsNearEdge(WinX, 0)) {
// Snap to left
SDL_SetWindowPosition(Window, 0, WinY);
} else if (IsNearEdge(WinX + 800, Display.w)) {
// Snap to right
SDL_SetWindowPosition(
Window, Display.w - 800, WinY);
}
}
Complete Snapping Implementation
Here's a more complete implementation that handles all edges and corners:
#include <SDL.h>
#include <cmath>
class Window { /*...*/ };
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
Window GameWindow;
SDL_Event E;
while (true) {
while (SDL_PollEvent(&E)) {
if (
E.type == SDL_WINDOWEVENT &&
E.window.event == SDL_WINDOWEVENT_MOVED
) {
GameWindow.SnapToEdges();
}
}
}
SDL_Quit();
return 0;
}
This implementation provides a smooth snapping effect when the window gets near any screen edge. The SnapDistance
constant determines how close to an edge the window needs to be before it snaps. You can adjust this value to make the snapping more or less sensitive.
Remember that this is a basic implementation - commercial window managers often include additional features like partial screen snapping (half-screen, quarter-screen) and multi-monitor support.
Managing Window Position
Learn how to control and monitor the position of SDL windows on screen