【问题标题】:C# Windows Form Label Font IssueC# Windows 窗体标签字体问题
【发布时间】:2012-01-04 07:21:09
【问题描述】:

我在一个 winform 应用程序中有一个自定义标签。我跨线程更改标签的内容。 我打开一个后台线程来读取输入数据,并调用我的跨线程方法来使用以下代码更改标签内容:

// ... invoke a cross-thread method to reset progress label information
Set_ProgressInfo("Reading data from input data file ... inputData");

我的跨线程方法是:

public void Set_ProgressInfo(string text)
{
    if (this.progressInfo.InvokeRequired)
    {
        this.progressInfo.BeginInvoke(new MethodInvoker(delegate()
            { Set_ProgressInfo(text); }));
    }
    else
    {
        this.progressInfo.Text = text;

        this.progressInfo.Location = new System.Drawing.Point(55, 595);
        this.progressInfo.ForeColor = System.Drawing.Color.AliceBlue;
        this.progressInfo.Font = new System.Drawing.Font("Verdana", 10.0f,
            System.Drawing.FontStyle.Bold);

        // Auto size label to fit the text
        // ... create a Graphics object for the label
        using (var g_progressInfo = this.progressInfo.CreateGraphics())
        {
           // ... get the Size needed to accommodate the formatted text
           Size preferredSize_progressInfo = g_progressInfo.MeasureString(
           this.progressInfo.Text, this.progressInfo.Font).ToSize();

           // ... pad the text and resize the label
           this.progressInfo.ClientSize = new Size(
           preferredSize_progressInfo.Width + (BSAGlobals.labelTextPadding),
           preferredSize_progressInfo.Height + (BSAGlobals.labelTextPadding));
       }
    }
}

一切都很好,因为它应该,除了:

当我改变字体大小时

this.progressInfo.Font = new System.Drawing.Font("Verdana", 10.0f,
    System.Drawing.FontStyle.Bold);

从 10.0f 到 8.0f,只有调用组件中字符串的“正在从输入数据文件读取数据...”部分

Set_ProgressInfo("Reading data from input data file ... inputData");

显示。由于某种原因,在较小的字体大小下无法正确计算大小。我在这里错过了什么吗?我已经为此苦苦挣扎了一段时间,根本看不出这是什么原因。任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 你没提,AutoSize=false?您是在设计器中还是在代码中更改字体大小?
  • 我正在更改代码中的大小,但我没有在任何地方设置 AutoSize。我正在以编程方式做所有事情。

标签: c# winforms label font-size


【解决方案1】:

您使用了错误的测量方法,请改用 TextRenderer.MeasureText()。 .NET 1.x 呈现方法 (Graphics.DrawString) 的字体指标不一样。从技术上讲,您应该同时使用两者,使用标签的 UseCompatibleTextRendering 属性的值,但可以轻松跳过。

最好使用标签的 Padding 和 AutoSize 属性,这样这一切都是自动的。

【讨论】:

  • 没想到这个。我会尝试并报告回来。当你说“从技术上讲,你应该同时使用两者,......”时,不确定你指的是什么。谢谢。
  • 我没有使用 MeasureText(),因为它不是很准确,但我使用 SetMeasurableCharacterRanges() 重新编码了您的建议。它产生同样的问题。由于某种原因,字符串文字在 ... 之后停止,但使用 System.Diagnostics.Debug.WriteLine(text) 会显示正确的文本。
【解决方案2】:

您是否尝试在更改字体大小后使控件无效?可以做的伎俩..

http://msdn.microsoft.com/en-us/library/598t492a.aspx

【讨论】:

  • 字体在运行时没有被改变。我想保持字体大小固定。我以新的大小重新编译,它发生了。所以这个解决方案不适用。不过谢谢。
猜你喜欢
  • 2011-07-06
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多