User Tools

Site Tools


center_window

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

center_window [2011/12/12 06:57] (current)
Line 1: Line 1:
 +====== Center a window or dialog ======
 +
 +It looks sometimes much better, if a new modal dialog or window is centered to his parent. This function solves this for you. just call ''​CenterWindow (hwndChild, hwndParent);''​.
 +
 +<code c>BOOL CenterWindow(HWND hwndChild, HWND hwndParent)
 +{
 +    RECT    rcChild, rcParent;
 +    int     ​cxChild,​ cyChild, cxParent, cyParent;
 +    int     ​cxScreen,​ cyScreen, xNew, yNew;
 +    HDC     hdc;
 +
 +    GetWindowRect(hwndChild,​ &​rcChild);​
 +    cxChild = rcChild.right - rcChild.left;​
 +    cyChild = rcChild.bottom - rcChild.top;​
 +
 +    GetWindowRect(hwndParent,​ &​rcParent);​
 +    cxParent = rcParent.right - rcParent.left;​
 +    cyParent = rcParent.bottom - rcParent.top;​
 +
 +    hdc = GetDC(hwndChild);​
 +    cxScreen = GetDeviceCaps(hdc,​ HORZRES);
 +    cyScreen = GetDeviceCaps(hdc,​ VERTRES);
 +    ReleaseDC(hwndChild,​ hdc);
 +
 +    xNew = rcParent.left + ((cxParent - cxChild) / 2);
 +    if (xNew < 0)
 +    {
 +        xNew = 0;
 +    }
 +    else if ((xNew + cxChild) > cxScreen)
 +    {
 +        xNew = cxScreen - cxChild;
 +    }
 +
 +    yNew = rcParent.top ​ + ((cyParent - cyChild) / 2);
 +    if (yNew < 0)
 +    {
 +        yNew = 0;
 +    }
 +    else if ((yNew + cyChild) > cyScreen)
 +    {
 +        yNew = cyScreen - cyChild;
 +    }
 +
 +    return SetWindowPos(hwndChild,​
 +                        NULL,
 +                        xNew, yNew,
 +                        0, 0,
 +                        SWP_NOSIZE | SWP_NOZORDER);​
 +}</​code>​
  
center_window.txt ยท Last modified: 2011/12/12 06:57 by crl