For a CFormView application, when the form size is changed, the margins around the controls in the form may appear to be unbalanced. When the form application is used on very different monitor resolutions, the same problem also appear. To make the controls automatically centralize while the form is resizing, the following procedure can be used:
- Put an invisible group box around all the controls in the form (make sure the tab order of the group box is the last).
- Add the handler for the message WM_SIZE (using the class wizard) OnSize(UINT nType, int cx, int cy) to the form view.
- Use the following code to the OnSize function:
void myFormView::OnSize(UINT nType, int cx, int cy)
CFormView::OnSize(nType, cx, cy);
// Don’t adjust position when scrollbars appear.
if ((GetScrollPos(SB_HORZ) != 0) || (GetScrollPos(SB_VERT) != 0))
int topMargin = 20, leftMargin = 20;
CRect rectView, rectTotal;
for (CWnd *wnd = GetWindow(GW_CHILD); wnd != NULL;
wnd = wnd->GetWindow(GW_HWNDNEXT))
CWnd *pWnd = GetDlgItem(IDC_TOTAL_RECT);
int xPos, yPos;
if(rectView.Width()>(rectTotal.Width() + 2*leftMargin))
xPos = (rectView.Width() – rectTotal.Width())/2;
xPos = leftMargin;
if(rectView.Height()>(rectTotal.Height() + 2*topMargin))
yPos = (rectView.Height() – rectTotal.Height())/2;
yPos = topMargin;
wnd->MoveWindow(xPos + rect.left – rectTotal.left,
yPos + rect.top – rectTotal.top,
rect.Width(), rect.Height(), TRUE);