Calculate the appropriete width of string if RichTextBox

  • 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
 
Hey Marcin,

Use can use either Graphics.MeasureString or Graphics.MeasureCharacterRanges
to measure the width of a given string. You can then set the widtch of the
RichTextBox to the found width. You can obtain a graphics object for your
RichTextBox by calling CreateGraphics on the RichTextBox. See the MSDN
documentation for examples of how to use MeasureString or
MeasureCharacterRanges.

HTH, Jakob.
 
Back
Top