How to calculate "physical" width of string

  • Thread starter Thread starter Marcin Waligora
  • Start date Start date
M

Marcin Waligora

Hi all,

I'm trying to create a read-only RichTextBox that will dynamically adjust
it's width to the string I throw into it.
It should be a perfect fit. I must use RichTextBox, because some of the text
can be in different color or be
bolded.

RichTextBox.Size doesn't work, since it is only an approximation.
Does anyone know how to calculate that??

Thanks,
Marcin Waligora
 
Hi Marcin,

Well, you can use MeasureCharacterRanges to get the exact size given the
font and control. Use that to set the RichTextBox size.
 
Hi,

It still is not trivial with RichTextBox. First because it may contain text
in different fonts, but mostly because there might be some other addornments
like bulet indents, indents or zoom
 
What about using the Graphics->MeasureString( String, Font ) method to
capture the width required? Then use the returned size to set your
RichTextBox up.

Dave
 
It has been identified that a RichTextBox is a mixture of many different fonts,
font sizes, and typographical stylings. He would have to call MeasureString
for every combination that exists in his RichTextBox to get the actual size.

If the insistance is still there to use this control, then I'd have to recommend
two things. The first is to ensure that there aren't any newline characters. You
can't, for instance, grow your control to fit the string, if it wraps itself. If
it
doesn't wrap itself, then grow your control in response to GetLineFromCharIndex
where you pass in the index of the last character. If you are double slick, you
can
do the entire process in without resizing more than once...

int lines = rtb.GetLineFromCharIndex(lastChar);
Point p = rtb.GetPositionFromCharIndex(lastChar);

rtb.Width = rtb.Width * (lines - 1) + (p.X);

I wrapped p.X because I'm not sure what coordinate system it is measure in. You
may have to do some math to find out how far from the edge of the control it is
in
case the point is in screen coordinates. To take a shorcut, just use the:

rtb.Width = rtb.Width * lines;
 
Hi,

You don't need to do any measurement at all, because RichTextBox has a very
little-known event called ContentSizeChanged, which is called everytime the
content of RichTextBox changes that causes an overflow out of the current
control size. Inside the event handler, you have access to the Rectangle
which will perfectly fit the new contents.

Hope that helps.

Dotnetjunky
 
Back
Top