c# - 如何更改 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。
解决方案
尝试使用自定义 RichTextBox 或将以下内容添加到您自己的自定义控件中。下面的代码没有考虑边框宽度,所以我确实添加了一个固定的偏移量(10)。
public class RichTextBoxCustom : RichTextBox
{
protected override void OnContentsResized(ContentsResizedEventArgs e)
{
base.OnContentsResized(e);
this.Height = e.NewRectangle.Height + 10;
}
}
推荐阅读
- api - 嘿,有人可以给我看一些关于 discord.py API 的代码吗?使用来自网站的 api
- python - 为开发设置沙盒容器环境的好方法是什么?
- python - 解包字典
- python - 如何从 sqlalchemy .execute() 方法中获取价值?Python + Sqlalchemy + MS SQL 服务器
- acumatica - 报表设计器中 Acumatica 中金额字段的文字表示
- python - 如何解决爬取GitHub问题正文时出现非法字符的问题?
- yocto - yocto如何支持ftp命令?
- python - 未找到 Anaconda3 Python shapely 模块
- sql - 在 Postgres (Redshift) 中使用两个选择列运行 MAX 聚合查询时出现问题
- r - 新的 Hugo 帖子未显示 - RMarkdown/Blogdown