c# Windows窗体标签字体问题



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

显示器。由于某些原因,在较小的字体大小下没有正确计算大小。我遗漏了什么吗?我已经为此挣扎了一段时间了,只是看不出其中的原因。任何帮助都将非常感激。谢谢你。

您正在使用错误的测量方法,请使用TextRenderer.MeasureText()代替。. net 1.0的字体度量。x渲染方法(Graphics.DrawString)是不一样的。从技术上讲,你应该使用两者,使用标签的UseCompatibleTextRendering属性的值,但这很容易被跳过。

请使用标签的Padding和AutoSize属性,这样这些都是自动的

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

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

最新更新