Measure Height

  • Thread starter Thread starter Jeremy Bradshaw
  • Start date Start date
J

Jeremy Bradshaw

How can I measure the height actually used by a TextBox control that shows
multiple lines (with word-wrap on) ? I want to size the textbox to only show
the number of lines actually needed to display all its text, rather than
have a number of blank lines at the end.
 
Lines only works when your text actually includes carriage returns - my text
is one long string which is wrapped in the textbox. However, I have got an
approximation of the number of lines actually occupied by using
MeasureString and seeing how many textbox length are needed to satisfy that,
however this doesn't always work because the nature of word wrapping means
that it doesnt always wrap at the whole width of the textbox, so I have to
add a fudge-factor, which can still mean that I get a blank line displayed
at the end. I was after something more accurate.
 
Ok, well thats easy then...

Something a bit like the control that's after my signature.
--
Bob Powell [MVP]
C#, System.Drawing

Check out the GDI+ FAQ
http://www.bobpowell.net/gdiplus_faq.htm

Buy quality Windows Forms tools
http://www.bobpowell.net/xray_tools.htm

New Tips and Tricks include creating transparent controls
and how to do double buffering.


---------------------------------------------------------------
using System;

using System.Drawing;

using System.Windows.Forms;



namespace TextPanel

{

/// <summary>

/// Summary.

/// </summary>

public class TextPanel : Control

{

private StringAlignment _alignment=StringAlignment.Near;

bool _internalSizing;



public TextPanel()

{

}



protected override void OnSizeChanged(EventArgs e)

{

if(_internalSizing)

_internalSizing=false;

else

CalcSize();

base.OnSizeChanged (e);

}



public StringAlignment Alignment

{

get{return _alignment;}

set{

_alignment=value;

Invalidate();

}

}



string _text;



public new string Text

{

get

{

return _text;

}

set

{

_text = value;

CalcSize();

}

}



void CalcSize()

{

Graphics g=CreateGraphics();



StringFormat sf=(StringFormat)StringFormat.GenericTypographic.Clone();

sf.Alignment=this.Alignment;

sf.FormatFlags=StringFormatFlags.NoClip;

SizeF size=g.MeasureString(this.Text,Font,new
SizeF(this.ClientSize.Width,this.ClientSize.Height),sf);

_internalSizing=true;

this.Size=new Size(this.Size.Width,(int)(size.Height+1));

}



protected override void OnPaint(PaintEventArgs e)

{



StringFormat sf=(StringFormat)StringFormat.GenericTypographic.Clone();

sf.Alignment=this.Alignment;

SolidBrush sb=new SolidBrush(this.ForeColor);

e.Graphics.DrawString(Text,Font,sb,this.ClientRectangle,sf);

sb.Dispose();



base.OnPaint (e);

}





}

}
 
Back
Top