Managing Window Position

Window Edge Snapping

How can I make my window snap to the edges of the screen like in Windows?

Abstract art representing computer programming

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.

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