C# RichTextBox行高自适应

第一种:

richTextBox1.ScrollBars = RichTextBoxScrollBars.None;
richTextBox.ContentsResized += new ContentsResizedEventHandler(richTextBox_ContentsResized);

  private void richTextBox1_ContentsResized(object sender, ContentsResizedEventArgs e)
  {
  richTextBox1.Height = e.NewRectangle.Height+10;

  }


第二种:

1.先调用以下方法:

          [DllImport("user32.dll", EntryPoint = "SendMessageA")]
          private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, string lParam);

2.设置RichTextBox:

            this.richTextBox1 = new RichTextBox();           
            this.richTextBox1.Text = “contentcontentcontentcontentcontentcontentcontentcontentcontent”;
            this.richTextBox1.Width = this.pPanel.Width-15;
            this.richTextBox1.ScrollBars = RichTextBoxScrollBars.None;
            this.richTextBox1.Location = new Point(0, 0 + this.lab1.Height+10);
           // this.richTextBox1.Anchor = (AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top);这句代码有问题
            //得到RichTextBox高度
            int EM_GETLINECOUNT = 0x00BA;//获取总行数的消息号 
            int lc = SendMessage(this.richTextBox1.Handle, EM_GETLINECOUNT, IntPtr.Zero, "");
            int sf = this.richTextBox1.Font.Height * (lc + 1) + this.richTextBox1.Location.Y;
            this.richTextBox1.Height = sf;
            this.richTextBox1.Resize += new EventHandler(richTextBox1_Resize);
            this.Controls.Add(this.richTextBox1);
3.设置RichTextBox的Resize:

        void richTextBox1_Resize(object sender, EventArgs e)
        {
            int EM_GETLINECOUNT = 0x00BA;//获取总行数的消息号 
            int lc = SendMessage(this.richTextBox1.Handle, EM_GETLINECOUNT, IntPtr.Zero, "");
            int sf = this.richTextBox1.Font.Height * (lc + 1) + this.richTextBox1.Location.Y;
            this.richTextBox1.Height = sf;
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值