Adjusting Control Size by Text Size

Click here to change the theme.

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:

  1. Wnd: A reference to a control, such as a CEdit or CStatic.
  2. Rect: Pointer to a RECT structure; the top-left coordinates determine the location of the control and the bottom-right coordinates should be set prior to the call to the size (relative to the bottom-right coordinates) of the text as determined by the GetTextSize function (shown below).
  3. Border: Should be CSize(0,0) for all controls except edit controls. Edit controls draw the WS_BORDER portion of their borders themselves, so this argument is intended to allow the calculation to be precise for edit controls also. It can be set to something such as:
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()); = Rect.left - AdjustedRect.left; = -;
AdjustedRect.right += << 1;
AdjustedRect.bottom += << 1;

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;
pdc = Wnd.GetDC();
CFont *pWndFont = Wnd.GetFont();
CFont *pPrevFont = pdc->SelectObject(pWndFont);
sizeText = pdc->GetTextExtent(s);