Click here to Skip to main content
15,894,362 members
Articles / Desktop Programming / MFC
Article

A Better CenterWindow() Function

Rate me:
Please Sign up or sign in to vote.
4.57/5 (4 votes)
3 Oct 2000 108.5K   778   21   11
This is a good replacement for CWnd::CenterWindow() that works.
  • Download demo project - 42.2 Kb
  • Sample Image - CenterAnywhere1.gif
    Figure 1. The main CenterSample sample program screen.

    Introduction

    Centering windows on the screen is something which you can normally do with the CWnd::CenterWindow() function in MFC. CenterWindow() 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 a pointer:

    pDlg->CenterWindow(AfxGetMainWnd()); // Centers pDlg against the main window?
    Listing 1. Demonstrating a use of CWnd::CenterWindow() 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 than CWnd::CenterWindow(). It's called CSubDialog::CenterWindowOnOwner(), and I added to my sample program's sub-dialog's class, CSubDialog:

    void CSubDialog::CenterWindowOnOwner(CWnd* pWndToCenterOn)
    {
        // Get the client rectangle of the window on which we want to center
        // Make sure the pointer is not NULL first
    
        if (pWndToCenterOn == NULL)
            return;
     
        CRect rectToCenterOn;
        pWndToCenterOn->GetWindowRect(&rectToCenterOn);
    
        // Get this window's area
        CRect rectSubDialog;
        GetWindowRect(&rectSubDialog);
    
        // Now rectWndToCenterOn contains the screen rectangle of the window 
        // pointed to by pWndToCenterOn.  Next, we apply the same centering 
        // algorithm as does CenterWindow()
    
        // find the upper left of where we should center to
    
        int xLeft = (rectToCenterOn.left + rectToCenterOn.right) / 2 - 
            rectSubDialog.Width() / 2;
        int yTop = (rectToCenterOn.top + rectToCenterOn.bottom) / 2 - 
            rectSubDialog.Height() / 2;
    
        // Move the window to the correct coordinates with SetWindowPos()
        SetWindowPos(NULL, xLeft, yTop, -1, -1,
            SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
    }
    Listing 2. Our brute-force CenterWindowOnOwner() function.

    Then I added code to CSubDialog::OnInitDialog() to center it with respect to the main dialog, which is the main window of the application:

    BOOL CSubDialog::OnInitDialog()
    {
        CDialog::OnInitDialog();
    
        ...
    
        CWnd* pMainWnd = AfxGetMainWnd();
        CenterWindowOnOwner(pMainWnd);
    
        return TRUE;
    }
    Listing 3.How to call CenterWindowOnOwner().

    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.

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here


    Written By
    Team Leader
    United States United States
    Dr. Brian Hart obtained his Ph.D. in Astrophysics from the University of California, Irvine in 2008. Under Professor David Buote, Dr. Heart researched the structure and evolution of the universe. Dr. Hart is currently employed as a Astrodynamicist / Space Data Scientist with Point Solutions Group in Colorado Springs, CO supporting Space Operations Command, United States Space Force. Dr. Hart is a Veteran of the U.S. Army and the U.S. Navy, having most recently served at Fort George G. Meade, MD as a Naval Officer with a Cyber Warfare Engineer designator. Dr. Hart has previously held positions at Jacobs Engineering supporting Cheyenne Mountain/Space Force supporting tests, with USSPACECOM/J58 supporting operators using predictive AI/ML with Rhombus Power, and with SAIC supporting the Horizon 2 program at STARCOM. Dr. Hart is well known to the community due to his over 150 technical publications and public speaking events. Originally from Minneapolis/Saint Paul, Minnesota, Dr. Hart lives in Colorado Springs with his Black Lab, Bruce, and likes bowling, winter sports, exploring, and swimming. Dr. Hart has a new movie coming out soon, which is a documentary called "Galaxy Clusters: Giants of the Universe," about his outer space research. The movie showcases the Chandra X-ray Observatory, one of NASA’s four great observatories and the world’s most powerful telescopes for detecting X-rays. The movie has been accepted for screening at the USAFA Planetarium and will highlight the need of updating and maintaining X-ray telescopes for scientific advancement.

    Comments and Discussions

     
    GeneralTruely multi-monitor aware CenterWindow code Pin
    ryltsov20-Jun-08 0:25
    ryltsov20-Jun-08 0:25 
    Even better multi-monitor aware fix for ATL CenterWindow is here:

    http://alax.info/blog/397[^]
    Generalcentering data inside a CMDIChildWnd Pin
    Anonymous18-Sep-04 20:33
    Anonymous18-Sep-04 20:33 
    GeneralMultiple-monitor support Pin
    Leo Davidson20-Jun-01 5:25
    Leo Davidson20-Jun-01 5:25 
    GeneralRe: Multiple-monitor support Pin
    Leo Davidson20-Jun-01 5:31
    Leo Davidson20-Jun-01 5:31 
    GeneralRe: Multiple-monitor support Pin
    1-Oct-01 12:15
    suss1-Oct-01 12:15 
    GeneralRe: Multiple-monitor support Pin
    _Stilgar_1-Mar-07 9:14
    _Stilgar_1-Mar-07 9:14 
    Generalbulletproof CenterWindow function for multi-monitors Pin
    Alfie Weinie13-Feb-01 13:38
    Alfie Weinie13-Feb-01 13:38 
    GeneralRe: bulletproof CenterWindow function for multi-monitors Pin
    yelena22s15-Aug-05 13:58
    yelena22s15-Aug-05 13:58 
    GeneralSuggestion Pin
    Dominic I. Holmes9-Oct-00 7:40
    Dominic I. Holmes9-Oct-00 7:40 
    GeneralCenter Form on CFormView Pin
    Gfw7-Oct-00 11:41
    Gfw7-Oct-00 11:41 
    GeneralRe: Center Form on CFormView Pin
    Virender Sandhu14-Nov-02 16:39
    Virender Sandhu14-Nov-02 16:39 

    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.