views:

498

answers:

3

Hi All

Can somebody please explain how I would go about measuring the string inside a richtextbox control so that the I can automatically resize the richtextbox control according to its content?

Thank you

Edit:

I've thought about it, and since the below answer won't work if there are different fonts in the RichTextBox Control, what if, I could get the upper-left coords of the richtextbox control and then get the bottom-right coords of the very last line of text inside the rtb. That would essentially give me the Width and Height of the string inside the RichTextBox Control. Is this possible? Or is this a bad idea to do it this way?

+1  A: 

You can measure a string by calling TextRenderer.MeasureText.

However, if the text contains multiple fonts, this will not work.

EDIT: You're looking for the GetPositionFromCharIndex method.
Note that if there are multiple lines, you should take the max of the X coordinates of the last character on each line.

SLaks
Thanks. I don't quite understand that page. Why does it draw text? Can it just send me back a width and height value, so I can reset the Size of the RichTextBox to the new size?
lucifer
Maybe if I ask a different question it would simplify things...
lucifer
`TextRenderer.MeasureText` doesn't draw anything; it simply returns the size of the text in pixels.
SLaks
A: 

Assuming that someone is typing into the control, you could use an event to fire every time a character is entered (increment counter) and decrement when it is deleted. This would give you a true count.

Edit:

Have you tried this to adjust the height?

richTextBox1.Height = (int)(1.5 * richTextBox1.Font.Height) + richTextBox1.GetLineFromCharIndex(richTextBox1.Text.Length + 1) * richTextBox1.Font.Height + 1 + richTextBox1.Margin.Vertical;

richTextBox1.SelectionStart = 0;

richTextBox1.SelectionStart = richTextBox1.Text.Length;

Or you can do this using Width:

Graphics g = Graphics.FromHwnd(richTextBox1.Handle);

SizeF f = g.MeasureString(richTextBox1.Text, richTextBox1.Font);
richTextBox1.Width = (int)(f.Width)+5;
0A0D
This is currently what I am doing, although you can't account for font styles/sizes this way, and eventually the rtb won't be able to keep up and the text would overflow
lucifer
see edit for height adjustment
0A0D
No offense, but this produces very ugly results. There has to be a way to do this without looking like the RichTextBox is about to explode through my monitor.
lucifer
Hmm, it seemed to work fine here but I am not applying any font styles
0A0D
A: 

Try calling GetPreferredSize(Size.Empty). It is defined in the Control class, and if overriden property by the RichTextBoxControl, ought to give you what you are looking for.

If you pass something other than Size.Empty into the method, then it will use that value as a maximum constraint. Using Size.Empty means that the potential size is unbounded.

Nick