C# RichTextBox高度隨內容動態變化
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 sf = this.richTextBox1.Font.Height * (lc + 1) + this.richTextBox1.Location.Y;
this.richTextBox1.Height = sf;
this.richTextBox1.Resize += new EventHandler(richTextBox1_Resize);
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;
}