Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofit WinForms RichTextBox to its contents

Does anybody know how can I dynamically resize a RichTextBox control to its contents?

like image 854
mrtaikandi Avatar asked Apr 09 '09 09:04

mrtaikandi


Video Answer


4 Answers

I guess I am far too late but take a look at this

It's just two code lines:

private void rtb_ContentsResized(object sender, ContentsResizedEventArgs e)
{
    ((RichTextBox)sender).Height = e.NewRectangle.Height + 5;
}
like image 199
dardo Avatar answered Oct 19 '22 05:10

dardo


Again assuming a fixed font could you do something like:

using (Graphics g = CreateGraphics())
{
    richTextBox.Height = (int)g.MeasureString(richTextBox.Text,
        richTextBox.Font, richTextBox.Width).Height;
}
like image 26
Luke North Avatar answered Oct 19 '22 03:10

Luke North


It's kind of a pain - the C# RichTextBox is often frustrating to work with. Are you trying to size the box big enough to hold its contents without any scrollbar?

If the RichTextBox has a constant font, you can use TextRenderer.MeasureText to simply measure the required size, and pass in the box's width as a constraint.

The ContentsResized event gives you a ContentsResizedEventsArgs, which gives you a NewRectangle which tells you how big the text area is. But it only fires when the text changes, which isn't as useful if you simply want to measure an existing richtextbox (although you could probably just do something hacky like set the box's text to itself, triggering this event).

There are also a bunch of Win32 api calls, like using EM_GETLINECOUNT (http://ryanfarley.com/blog/archive/2004/04/07/511.aspx), etc.

like image 4
jean Avatar answered Oct 19 '22 03:10

jean


A really cheap solution (one that is potentially fraught with problems) is to simultaneously fill an autofit label with text using the same font and size, then just copy the width of the label to the width of the RTB.

So, like this:

RichTextBox rtb = new RichTextBox();
rtb.Text = "this is some text";
rtb.Font = new Font("Franklin Gothic Medium Cond", 10, FontStyle.Regular);

Label fittingLabel = new Label();
fittingLabel.Text = rtb.Text;
fittingLabel.Font = rtb.Font;
fittingLabel.AutoSize = true;

//Not sure if it's necessary to add the label to the form for it to autosize...
fittingLabel.Location = new Point(-1000,-1000);
this.Controls.Add(fittingLabel);

rtb.Width = fittingLabel.Width;

this.Controls.Remove(fittingLabel);
like image 3
user1112234 Avatar answered Oct 19 '22 03:10

user1112234