The Grimoire of Nonsense

個人的なメモを残すブログ

超中央にウィンドウを配置するための計算

画面のど真ん中にウィンドウを配置するときの計算方法をば。
タスクバーを除く画面の作業領域のサイズをSystemParametersInfo()で取得し、
タイトルバーの高さをtitleBarSize()で取得する。
詳しくは駄文を参照いただければよろしいかと。


例えば、Fallout4を画面サイズ1600x900で中央に配置するときはX位置が160、Y位置が47という値になる*1

#include <cstdio>
#include <Windows.h>
using namespace std;

int main()
{
	const int width = 1600;	// ウィンドウの横幅
	const int height = 900;	// ウィンドウの縦幅
	RECT rect = { 0 };		// 画面領域のサイズ
	int titleBarSize = 0;	// タイトルバーのサイズ

	// 作業領域のサイズを取得
	SystemParametersInfo( SPI_GETWORKAREA, 0, &rect, 0 );

	// タイトルバーのサイズを取得
	titleBarSize = GetSystemMetrics( SM_CYCAPTION );

	printf( "X Location: %d\n", ( rect.right - width ) / 2 );
	printf( "Y Location: %d\n", ( ( rect.bottom - height ) / 2 ) - titleBarSize );

	return 0;
}

*1:Windows 10で動かしたときの結果なので他OSなら若干変わる可能性があります。