RichTextBox自动高度

 private void richTextBox1_ContentsResized(object sender, ContentsResizedEventArgs e)
        {
            var richTextBox = (RichTextBox)sender;
            //    richTextBox.Width = e.NewRectangle.Width;
            int lineheight = richTextBox.Font.Height;
            int nHeight = lineheight;
            if (e.NewRectangle.Height < lineheight)
                nHeight = lineheight;
            else
                nHeight = e.NewRectangle.Height+ lineheight;
            richTextBox.Height = nHeight;
        }

网上找了好多办法,就这个最省事和简单,参考https://stackoverflow.com/questions/11906932/size-richtextbox-according-to-contents

Have you looked at the ContentsResized event? Add the following method to be called when the event fires:

private void richTextBox_ContentsResized(object sender, ContentsResizedEventArgs e)
{
    var richTextBox = (RichTextBox) sender;
    richTextBox.Width = e.NewRectangle.Width;
    richTextBox.Height = e.NewRectangle.Height;
}

When the RTF content is changed (using Rtf), the RichTextBox should be resized to match its contents. Make sure you also set the WordWrap property to false.


I've tried it with your table example and it does appear to work (albeit with a little offset, which you could possibly solve by adding a few pixels of width to the adjusted size - not sure why that happens):

P.Brian.Mackey EDIT
This answer worked for me. To clarify, here's the final code including border fix:

    public static void Main()
    {
        string sInput = "hi\t bye\t\n";// one\t two\t\n";
        SIZE CharSize;
        Form form = new Form();
        RichTextBox rtfBox = new RichTextBox();
        rtfBox.ContentsResized += (object sender, ContentsResizedEventArgs e) =>
        {
            var richTextBox = (RichTextBox)sender;
            richTextBox.Width = e.NewRectangle.Width;
            richTextBox.Height = e.NewRectangle.Height;
            rtfBox.Width += rtfBox.Margin.Horizontal + SystemInformation.HorizontalResizeBorderThickness;
        };

        rtfBox.WordWrap = false;
        rtfBox.ScrollBars = RichTextBoxScrollBars.None;

        rtfBox.Rtf = @"{\rtf1\ansi\deff0{\fonttbl{\f0\fnil Arial;}}\viewkind4\uc1\trowd\trgaph100\cellx1000\cellx2000\pard\intbl\lang1033\f0\fs20  hi\cell  bye\cell\row\intbl  one\cell  two\cell\row\pard\par}";

        form.Controls.Add(rtfBox);
        form.ShowDialog();
    }
shareimprove this answer
posted @ 2017-11-06 10:36  tr菩提树  阅读(344)  评论(0编辑  收藏  举报