<!-- Link to demo file download -->
Download demo project - 42.2 Kb
<!-- Article image -->
Figure 1. The main
CenterSample sample program screen.
<!-- Add the rest of your HTML here -->
Centering windows on the screen is something which you can normally do with the
CWnd::CenterWindow() function in MFC.
takes a pointer to a
CWnd as its argument, and supposedly the function
will center the window on which it's called against the window to which you pass it
Demonstrating a use of
to center a dialog.
However, a question posed to the MFC Mailing List
recently asked, "I have a dialog-based program, where the user can click a button and
have a sub-dialog pop up. If I call
CWnd::CenterWindow() in the sub-dialog's
OnInitDialog() handler, the dialog will always be centered in the center
of the screen, not centered with respect to the main dialog. How do I do this?"
So I came up with a "Brute Force" centering function which actually works better
CWnd::CenterWindow(). It's called
CSubDialog::CenterWindowOnOwner(), and I added to my sample program's
void CSubDialog::CenterWindowOnOwner(CWnd* pWndToCenterOn)
if (pWndToCenterOn == NULL)
int xLeft = (rectToCenterOn.left + rectToCenterOn.right) / 2 -
rectSubDialog.Width() / 2;
int yTop = (rectToCenterOn.top + rectToCenterOn.bottom) / 2 -
rectSubDialog.Height() / 2;
SetWindowPos(NULL, xLeft, yTop, -1, -1,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
Then I added code to
CSubDialog::OnInitDialog() to center it with respect
to the main dialog, which is the main window of the application:
CWnd* pMainWnd = AfxGetMainWnd();
How to call
And voila! The sub-dialog will always center itself on the main dialog (or main
application window), no matter where on the screen that window is placed.