Centering a Dialog Box on the Screen

Last reviewed: November 2, 1995
Article ID: Q74798
The information in this article applies to:
  • Microsoft Windows Software Development Kit (SDK) versions 3.1
  • Microsoft Win32 Application Programming Interface (API) included with:

        - Microsoft Windows NT versions 3.5 and 3.51
    

When an application developed for the Microsoft Windows graphical environment displays a dialog box, centering the dialog box on the screen is sometimes desirable. However, on systems with high- resolution displays, the application displaying the dialog box may be nowhere near the center of the screen. In these cases, it is preferable to place the dialog near the application requesting input.

To center a dialog box on the screen before it is visible, add the following lines to the processing of the WM_INITDIALOG message:

    {
    RECT rc;

    GetWindowRect(hDlg, &rc);

    SetWindowPos(hDlg, NULL,
       ((GetSystemMetrics(SM_CXSCREEN) - (rc.right - rc.left)) / 2),
       ((GetSystemMetrics(SM_CYSCREEN) - (rc.bottom - rc.top)) / 2),
       0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
    }

This code centers the dialog horizontally and vertically.

Under Windows 95, you should use the new style DS_CENTER to get the same effect.


Additional reference words: 3.00 3.10 3.50
KBCategory: kbui
KBSubcategory: UsrDlgs


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: November 2, 1995
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.