Visual C++ 10.0Visual C++ 9.0Visual C++ 8.0Visual C++ 7.0Windows 7Windows 2000Visual C++ 6.0Windows XPWindowsC++
CenterWindow in WIN32






4.86/5 (7 votes)
How to center window in WIN32
In MFC, there is
CWnd::CenterWindow
, but to do this in WIN32, you need the following code:
BOOL CenterWindow(HWND hwndWindow)
{
HWND hwndParent;
RECT rectWindow, rectParent;
// make the window relative to its parent
if ((hwndParent = GetParent(hwndWindow)) != NULL)
{
GetWindowRect(hwndWindow, &rectWindow);
GetWindowRect(hwndParent, &rectParent);
int nWidth = rectWindow.right - rectWindow.left;
int nHeight = rectWindow.bottom - rectWindow.top;
int nX = ((rectParent.right - rectParent.left) - nWidth) / 2 + rectParent.left;
int nY = ((rectParent.bottom - rectParent.top) - nHeight) / 2 + rectParent.top;
int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
// make sure that the dialog box never moves outside of the screen
if (nX < 0) nX = 0;
if (nY < 0) nY = 0;
if (nX + nWidth > nScreenWidth) nX = nScreenWidth - nWidth;
if (nY + nHeight > nScreenHeight) nY = nScreenHeight - nHeight;
MoveWindow(hwndWindow, nX, nY, nWidth, nHeight, FALSE);
return TRUE;
}
return FALSE;
}