Multiple Windows and Utility Windows

Handling Multi-Window Events

How does SDL handle events when there are multiple windows?

Abstract art representing computer programming

SDL provides robust support for managing multiple windows in an application. Each window created with SDL_CreateWindow() is assigned a unique identifier (windowID), which SDL uses to associate events with the correct window.

Event Structure

When an event occurs that relates to a specific window, like a resize or keypress, the event structure includes the windowID. This allows your program to determine which window the event corresponds to.

For example, in a SDL_WindowEvent:

if (event.type == SDL_WINDOWEVENT) {
  std::cout << "Event for Window ID: "
            << event.window.windowID << '\n';
}

Retrieving the Window

To get the SDL_Window* associated with an event, use SDL_GetWindowFromID():

SDL_Window* window = SDL_GetWindowFromID(
  event.window.windowID);
if (window) {
  SDL_SetWindowTitle(
    window, "Event Triggered"
  );
}

Example Use Case

Imagine a multi-window text editor. Each window represents a document, and resizing one window shouldn’t affect the others. Here’s a simplified example:

void HandleResize(SDL_WindowEvent& event) {
  SDL_Window* window =
    SDL_GetWindowFromID(event.windowID);
  if (window) {
    std::cout << "Resized window with ID "
      << event.windowID << '\n';
  }
}

void ProcessEvents() {
  SDL_Event event;
  while (SDL_PollEvent(&event)) {
    if (event.type == SDL_WINDOWEVENT &&
        event.window.event == SDL_WINDOWEVENT_RESIZED) {
      HandleResize(event.window);
    }
  }
}

Using window IDs ensures you can efficiently manage events for each window independently, enabling complex multi-window applications.

This Question is from the Lesson:

Multiple Windows and Utility Windows

Learn how to manage multiple windows, and practical examples using utility windows.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Multiple Windows and Utility Windows

Learn how to manage multiple windows, and practical examples using utility windows.

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:

  • 67 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