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;
        }


發佈了29 篇原創文章 · 獲贊 41 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章