65.9K
CodeProject is changing. Read more.
Home

Height of Text

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.63/5 (6 votes)

Jun 24, 2004

viewsIcon

40466

This function will return the height of text. Designed for use with text boxes on windows forms.

Introduction

This is a handy little function for getting the height of text. 

Overview

I have read many articles and asked lots of questions before I found the functions in the dot net library that would help me to achieve this task.

This is also my very first Code Project article. This site has helped me solve MANY problems and I hope that this piece of code helps someone out.

The Code


  /// <summary>
  /// This method will return the height of the string passed in.
  /// </summary>
  /// <param name="strMeasureString">The string to measure</param>
  /// <param name="stringFont">The font to measure by</param>
  /// <param name="nWidth">The max width the string can be [Width of the text box usually ;)]</param>
  /// <param name="hwnd">Handle to your form so I can get the graphics object</param>  
  /// <returns>The height of the string as a int</returns>

 

public int GetStringHeight(string strMeasureString, System.Drawing.Font stringFont, int nWidth,System.IntPtr hwnd)

{

using (System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(hwnd))

{

return (int)g.MeasureString(strMeasureString, stringFont, nWidth).Height;

}

}

(Thanks for the advice Micheal)

Its pretty straightforward and it creates some pretty cool effects if you use it with the 'Text Changed' event of a text box. Tie that to the 'Resize' event and you can have a form the grows and shrinks as the user is typing in text.