I have a custom label in a winform app. I change the content of the label across threads.
I open a background thread to read input data, and I call my cross-thread method to change the label content using the following code:
// ... invoke a cross-thread method to reset progress label information
Set_ProgressInfo("Reading data from input data file ... inputData");
My cross-thread method is:
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));
}
}
}
Everything works great, as it should, except:
When I change the font size in
this.progressInfo.Font = new System.Drawing.Font("Verdana", 10.0f,
System.Drawing.FontStyle.Bold);
from 10.0f to 8.0f, only the “Reading data from input data file …” portion of the string in the calling component
Set_ProgressInfo("Reading data from input data file ... inputData");
displays. For some reason the size is not being calculated correctly at the smaller font size. Am I missing something here? I have been struggling with this for some time now and simply cannot see the reason for this. Any help would be greatly appreciated. Thank you.
You are using the wrong measuring method, use TextRenderer.MeasureText() instead. The font metrics for the .NET 1.x rendering method (Graphics.DrawString) isn’t the same. Technically you should use both, using the value of the label’s UseCompatibleTextRendering property, but that can easily be skipped.
Do favor using the label’s Padding and AutoSize properties so this is all automatic.