The AdjustWindowSize sample function shown below determines the size of text in a control, then resizes the control to that size plus the border size. It has been tested with edit and static controls only. Your requirements might be different, of course, but this sample could be useful for other uses also. This function has been used with single-line edit controls and with static controls with heights for only a single line of text. The function will probably need to be modified for multiline controls. I have not thought for even a second about what changes might be needed for multiline controls.
Prior to use of this function, the text is put into the control and then the GetTextSize function (also shown below) is used to determine the size of the text in the control. The AdjustWindowSize function has three parameters:
CSize(GetSystemMetrics(SM_CXBORDER) << 1, GetSystemMetrics(SM_CYBORDER) << 1);
void CBordersView::AdjustWindowSize(CRect &Rect, CSize &Border) {
CRect AdjustedRect(Rect);
SIZE Size;
AdjustWindowRectEx(AdjustedRect, Wnd.GetStyle(), FALSE, Wnd.GetExStyle());
Size.cx = Rect.left - AdjustedRect.left;
Size.cy = Rect.top - AdjustedRect.top;
AdjustedRect.OffsetRect(Size);
AdjustedRect.right += Border.cx << 1;
AdjustedRect.bottom += Border.cy << 1;
Wnd.MoveWindow(&AdjustedRect);
}
I discovered that AdjustWindowRectEx inflates the rectangle, so the OffsetRect moves the control (if applicable) back to the position specified by the Rect parameter.
The following function is used to determine the size of the text in the control (see above).
void CBordersView::GetTextSize(CWnd &Wnd, CSize &sizeText) {
CString s;
CDC *pdc;
Wnd.GetWindowText(s);
pdc = Wnd.GetDC();
CFont *pWndFont = Wnd.GetFont();
CFont *pPrevFont = pdc->SelectObject(pWndFont);
sizeText = pdc->GetTextExtent(s);
pdc->SelectObject(pPrevFont);
Wnd.ReleaseDC(pdc);
}
See my Visual C++ Programmer Stuff page for more C++ stuff.