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(); }
share improve this answer

转载于:https://www.cnblogs.com/trphoenix/p/7791996.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值