Click here to Skip to main content
12,998,785 members (70,331 online)
Click here to Skip to main content
Add your own
alternative version


7 bookmarked
Posted 7 Sep 2011

CenterWindow in WIN32

, 2 Oct 2011
Rate this:
Please Sign up or sign in to vote.
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 -;
         int nX = ((rectParent.right - rectParent.left) - nWidth) / 2 + rectParent.left;
         int nY = ((rectParent.bottom - - nHeight) / 2 +;
         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;


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mihai MOGA
Architect Printec Group Romania SRL
Romania Romania
My professional background includes knowledge of analyst programmer for Microsoft Visual C++, Microsoft Visual C#, Microsoft Visual Basic, Sun Java, assembly for Intel 80x86 microprocessors, assembly for PIC microcontrollers (produced by Microchip Inc.), relational databases (MySQL, Oracle, SQL Server), concurrent version systems, bug tracking systems, web design (XHTML, CSS, XML, PHP/MySQL, JavaScript, Flash).

If you like my articles, please visit my website for more:

You may also be interested in...

Comments and Discussions

QuestionThank you, Cap Pin
Slava200912-Sep-11 20:03
memberSlava200912-Sep-11 20:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170622.1 | Last Updated 2 Oct 2011
Article Copyright 2011 by Mihai MOGA
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid