How To Calculate the Height of Edit Control to Resize It (124315)



The information in this article applies to:

  • Microsoft Windows Software Development Kit (SDK) 3.1
  • Microsoft Win32 Software Development Kit (SDK) 3.5
  • Microsoft Win32 Software Development Kit (SDK) 3.51

This article was previously published under Q124315

SUMMARY

When a program changes the font of an edit control, it must calculate the new height of the control so that text is displayed correctly. When an edit control contains a border, the control automatically adds white space around the text so the text won't interfere with the border.

This article shows by example how a program can modify the height of an edit control so that text displayed in the control looks right after the program changes the font.

MORE INFORMATION

The height of the control on creation is calculated as the height of the control's font plus half of the smaller of the height of the control's font or the height of the system font. You can use a function similar to the one below to calculate the new height of an edit control when the font in the control is changed.

Sample Code

   void ResizeEdit(HWND hwndEdit, HFONT hNewFont)
   {
      HFONT       hSysFont,
                  hOldFont;
      HDC         hdc;
      TEXTMETRIC  tmNew,
                  tmSys;
      RECT        rc;
      int         nTemp;

      // Get the DC for the edit control.
      hdc = GetDC(hwndEdit);

      // Get the metrics for the system font.
      hSysFont = GetStockObject(SYSTEM_FONT);
      hOldFont = SelectObject(hdc, hSysFont);
      GetTextMetrics(hdc, &tmSys);

      // Get the metrics for the new font.
      SelectObject(hdc, hNewFont);
      GetTextMetrics(hdc, &tmNew);

      // Select the original font back into the DC and release the DC.
      SelectObject(hdc, hOldFont);
      DeleteObject(hSysFont);
      ReleaseDC(hwndEdit, hdc);

      // Calculate the new height for the edit control.
      nTemp = tmNew.tmHeight + (min(tmNew.tmHeight, tmSys.tmHeight)/2) +
      (GetSystemMetrics(SM_CYEDGE) * 2);

      // Re-size the edit control.
      GetWindowRect(hwndEdit, &rc);
      MapWindowPoints(HWND_DESKTOP, GetParent(hwndEdit), (LPPOINT)&rc, 2);
      MoveWindow( hwndEdit,
                  rc.left,
                  rc.top,
                  rc.right - rc.left,
                  nTemp,
                  TRUE);
   }
				

Modification Type:MinorLast Reviewed:6/29/2004
Keywords:kbEditCtrl kbhowto KB124315