While letting the operating system handle window positioning works well for basic applications, there are several compelling reasons to take control of window positioning:
Many games and applications need precise window control for specific features:
Custom window positioning can significantly improve user experience:
#include <SDL.h>
#include "Window.h"
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
// Create a main window centered on screen
SDL_Window* MainWindow{
SDL_CreateWindow(
"Main Window",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
800, 600, 0
)
};
// Create a toolbar window that sits above
// the main window
int mainX, mainY;
SDL_GetWindowPosition(
MainWindow, &mainX, &mainY);
SDL_Window* ToolWindow{
SDL_CreateWindow(
"Tools",
// Position above main window
mainX, mainY - 100,
800, 80, 0
)
};
SDL_Delay(5000);
SDL_Quit();
return 0;
}
We can remember where users like their windows and restore those positions later:
#include <SDL.h>
#include <fstream>
void SaveWindowPosition(
SDL_Window* Window, const char* Filename
) {
int x, y;
SDL_GetWindowPosition(Window, &x, &y);
std::ofstream File{Filename};
File << x << ' ' << y;
}
void RestoreWindowPosition(
SDL_Window* Window, const char* Filename
) {
std::ifstream File{Filename};
int x, y;
if (File >> x >> y) {
SDL_SetWindowPosition(Window, x, y);
}
}
Control over window positioning helps create a more polished, professional feel:
While the operating system's default positioning is a good starting point, taking control of window positioning when needed can significantly enhance your application's usability and professional feel.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to control and monitor the position of SDL windows on screen