The blog of Tobin

Tobins nerd blog on .NET, Software, Tech and Nice Shiny Gadgets.

Wednesday, December 01, 2004

TextBox Auto Fit to Size

I was recently trying to get a textbox to grow depending on how much text there was in it. This is quite simple if you're NOT using word wrap - but if you are it's a real pain in the arse!

The basic approach is to capture the TextChanged event, and then work out how many lines there are, and then how high each line is. This is all really easy, except working out how many lines there are. The textbox has a .Lines.Length property, but this won't be adjusted if you have word wrap on.


Anyway, after ages of searching and trying out different things, I stumbled across the most simple thing that just seems to work!


Here it is...


public static int GetLineCount( TextBoxBase textbox )
{
const int EM_GETLINECOUNT = 186;
return SendMessage(
textbox.Handle, EM_GETLINECOUNT, 0, 0 );
}

Once you have this, you can do something like this to get make your text box grow to the correct size.


Graphics g = _textBox.CreateGraphics();

float size = _textBox.Font.GetHeight(
_textBox.CreateGraphics()
) * (float) 1.075;

_textBox.Height = Convert.ToInt32(
( TextBoxMeasure.GetLineCount(
_textBox ) 1) * size
);

0 Comments:

Post a Comment

<< Home