Hi, my first post to the boards so hello! Ive written a class that will auto size the height of a label based on the text inside. It works fine for normal text, but if I make the text bold it seems to ignore that its bold and still measure the label as if it was regular text. This means it wont resize the label properly. I have to have this working for bold text! Does anyone have any ideas how I can modify it to work with bold text?
Here is an example of how I would call the method. If I change it from bold to regular the measurement is the same.
Code:
public class clsAutoSizeLabel
{
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
[DllImport("user32.dll")]
private static extern int DrawText(IntPtr hDC, string lpString, int nCount, ref RECT lpRect, uint uFormat);
[DllImport("gdi32.dll")]
private static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
private const int DT_CALCRECT = 0x400;
private const int DT_WORDBREAK = 0x10;
public static void AutoSizeLabelHeight(Label ctlLabel)
{
RECT uRECT;
uRECT.Left=0;
uRECT.Top=0;
uRECT.Right=0;
uRECT.Bottom=0;
try
{
Graphics objGraphics = ctlLabel.CreateGraphics();
IntPtr hDc = objGraphics.GetHdc();
IntPtr hFont = ctlLabel.Font.ToHfont();
IntPtr hFontOld = SelectObject(hDc, hFont);
uRECT.Right = ctlLabel.Width - 4;
if(DrawText(hDc, ctlLabel.Text, -1, ref uRECT, DT_CALCRECT | DT_WORDBREAK) != 0)
ctlLabel.Height = uRECT.Bottom + 4;
SelectObject(hDc, hFontOld);
DeleteObject(hFont);
objGraphics.ReleaseHdc(hDc);
objGraphics.Dispose();
}
catch
{
}
}
}
Here is an example of how I would call the method. If I change it from bold to regular the measurement is the same.
Code:
myLabel.Font = new System.Drawing.Font("Verdana", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
myLabel.Location = new System.Drawing.Point(168, 8);
myLabel.Name = "myLabel";
myLabel.Size = new System.Drawing.Size(432, 32);
myLabel.Text = "This is the text inside the label, but it dosnt seem to work properlly when I use bold!";
myLabel.BackColor = System.Drawing.Color.Blue; // set background to blue so we can see the sizing properly
clsAutoSizeLabel.AutoSizeLabelHeight(myLabel);
this.Controls.Add(myLabel);