Measure String inside RichTextBox Control

后端 未结 6 1015
刺人心
刺人心 2020-12-19 02:44

Can somebody please explain how I would go about measuring the string inside a richtextbox control so that the I can automatically resize the richtextbox control according t

6条回答
  •  佛祖请我去吃肉
    2020-12-19 03:20

    Assuming that someone is typing into the control, you could use an event to fire every time a character is entered (increment counter) and decrement when it is deleted. This would give you a true count.

    Edit:

    Have you tried this to adjust the height?

    richTextBox1.Height = (int)(1.5 * richTextBox1.Font.Height) + richTextBox1.GetLineFromCharIndex(richTextBox1.Text.Length + 1) * richTextBox1.Font.Height + 1 + richTextBox1.Margin.Vertical;
    
    richTextBox1.SelectionStart = 0;
    
    richTextBox1.SelectionStart = richTextBox1.Text.Length;
    

    Or you can do this using Width:

    Graphics g = Graphics.FromHwnd(richTextBox1.Handle);
    
    SizeF f = g.MeasureString(richTextBox1.Text, richTextBox1.Font);
    richTextBox1.Width = (int)(f.Width)+5;
    

提交回复
热议问题