C#Windows窗体标签字体问题

时间:2011-11-22 22:26:48

标签: c# winforms label font-size

我在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");

显示器。由于某种原因,在较小的字体大小下没有正确计算大小。我在这里错过了什么吗?我一直在努力解决这个问题一段时间,根本看不出原因。任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:2)

您使用的是错误的测量方法,请改用TextRenderer.MeasureText()。 .NET 1.x呈现方法(Graphics.DrawString)的字体度量标准不相同。从技术上讲,你应该使用标签的UseCompatibleTextRendering属性的值,但是可以很容易地跳过它。

请使用标签的Padding和AutoSize属性,因此这是全自动的。

答案 1 :(得分:1)

更改字体大小后,您是否尝试使控件无效?可以做到这一点..

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