How to create a new window in SDL that is inserted into the main window? So it could be focused, have separate drawing context and process events separately.
You can create a window within a window using the example below. The example will spawn two windows, where subWindow is inside mainWindow. The sub window can be moved out of the main window. If you want the sub window to be "stuck" inside the main window, you could use the SDL_WindowEvent to see when the window was moved and then force it back into place using SDL_SetWindowPosition()
You can't do this in SDL2 as far as I know. But some, if not all, event type has the windowID member variable. Use this along with SDL_GetWindowID() on your SDL_Windows to find which window had the focus at the time of the event.
#include <SDL2/SDL.h>
#include <iostream>
int main()
{
SDL_Init( SDL_INIT_EVERYTHING );
// Set postion and size for main window
int mainSizeX = 600;
int mainSizeY = 600;
int mainPosX = 100;
int mainPosY = 100;
// Set postion and size for sub window based on those of main window
int subSizeX = mainSizeX / 2;
int subSizeY = mainSizeY / 2;
int subPosX = mainPosX + mainSizeX / 4;
int subPosY = mainPosY + mainSizeY / 4;
// Set up main window
SDL_Window* mainWindow = SDL_CreateWindow( "Main Window", mainPosX, mainPosY, mainSizeX, mainSizeY, 0 );
SDL_Renderer* mainRenderer = SDL_CreateRenderer( mainWindow, -1, SDL_RENDERER_ACCELERATED );
SDL_SetRenderDrawColor( mainRenderer , 255, 0, 0, 255 );
// Set up sub window
SDL_Window* subWindow = SDL_CreateWindow( "Sub Window" , subPosX, subPosY, subSizeX, subSizeY, 0 );
SDL_Renderer* subRenderer = SDL_CreateRenderer( subWindow, -1, SDL_RENDERER_ACCELERATED );
SDL_SetRenderDrawColor( subRenderer , 0, 255, 0, 255 );
// Render empty ( red ) background in mainWindow
SDL_RenderClear( mainRenderer );
SDL_RenderPresent( mainRenderer );
// Render empty ( green ) background in subWindow
SDL_RenderClear( subRenderer );
SDL_RenderPresent( subRenderer );
std::cin.ignore();
}
This example will render a green window with half the width and height in the middle of a red window.
In case someone is wondering how to render child window always on top of parent window and avoid problem with input focus on parent window:
SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH to "1".SDL_RiseWindow on each child when parent window receives SDL_WINDOWEVENT_FOCUS_GAINEDIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With