如何更改RichTextBox的高度以适合C#中的新字体大小

时间:2019-04-24 15:50:46

标签: c# resize richtextbox

我的应用程序允许用户更改RichTextBox中使用的字体,包括字体大小。我遇到的问题是,尽管字体大小按预期变化,但RichTextBox的高度却没有相应变化。需要保持RichTextBox的高度,以便仅显示一行文本就足够了。

更改字体后,RichTextBox可能不包含任何文本,因此我目前正在尝试像这样设置新高度:

Font FONT = new System.Drawing.Font("Microsoft Sans Serif", 27F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
var height = TextRenderer.MeasureText("|", FONT).Height;
this.richTextBoxInput.Height = height;

即使执行代码,RichTextBox的高度也不会改变。这是我如何初始化的方法:

this.richTextBoxInput.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
this.richTextBoxInput.BackColor = System.Drawing.Color.White;
this.richTextBoxInput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.richTextBoxInput.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.richTextBoxInput.Location = new System.Drawing.Point(50, 52);
this.richTextBoxInput.Margin = new System.Windows.Forms.Padding(0);
this.richTextBoxInput.Name = "richTextBoxInput";
this.richTextBoxInput.ReadOnly = false;
this.richTextBoxInput.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;
this.richTextBoxInput.Size = new System.Drawing.Size(200, 20);
this.richTextBoxInput.TabIndex = 0;
this.richTextBoxInput.TabStop = false;
this.richTextBoxInput.Text = "<Input>";

有人知道如何进行这项工作吗?我正在使用.NET 4.5。

1 个答案:

答案 0 :(得分:0)

尝试使用自定义RichTextBox或将以下内容添加到您自己的自定义控件中。 以下代码未考虑边框宽度,因此我确实添加了固定的偏移量(10)。

    public class RichTextBoxCustom : RichTextBox
    {
        protected override void OnContentsResized(ContentsResizedEventArgs e)
        {
            base.OnContentsResized(e);
            this.Height = e.NewRectangle.Height + 10;
        }
    }