首页 > 解决方案 > 如何更改 RichTextBox 高度以适应 C# 中的新字体大小

问题描述

我的应用程序允许用户更改在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。

标签: c#resizerichtextbox

解决方案


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

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

推荐阅读