Creating A Label That Displays A Path With Middle-Ellipsis

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi,

Ive created the following class in order to display path names in a label within a dialog:
class PathLabel : System.Windows.Forms.Label
{
    protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.Clear(this.BackColor);
        System.Drawing.StringFormat sf = System.Drawing.StringFormat.GenericDefault;
        sf.Trimming = System.Drawing.StringTrimming.EllipsisPath;
        e.Graphics.DrawString(this.Text, this.Font, new System.Drawing.SolidBrush(this.ForeColor), 0, 0, sf);
    }
}

Or, in another version of it:

class PathLabel : System.Windows.Forms.Label
{
    protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.Clear(this.BackColor);
        System.Windows.Forms.TextRenderer.DrawText(e.Graphics, this.Text, this.Font, new System.Drawing.Point(0, 0), this.ForeColor, this.BackColor, System.Windows.Forms.TextFormatFlags.PathEllipsis);
    }
}

Then I added such a label to my dialog using a code similiar to the following:

private EnhancedControls.PathLabel labelSelectedDirectory;
private void InitializeComponent()
{
    this.labelSelectedDirectory = new EnhancedControls.PathLabel();
    ...
}


private void InitializeComponent()
{
    this
.labelSelectedDirectory.AutoEllipsis = true;
    this.labelSelectedDirectory.AutoSize = false;
    this.labelSelectedDirectory.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
    this.labelSelectedDirectory.Location = new System.Drawing.Point(192, 23);
    this.labelSelectedDirectory.Name = "labelSelectedDirectory";
    this.labelSelectedDirectory.Size = new System.Drawing.Size(287, 15);
    this.labelSelectedDirectory.TabIndex = 20;
    this.labelSelectedDirectory.Text = " ";
    this.Controls.Add(this.labelSelectedDirectory);
    ...
}

BUT when I run my app (never mind with which of above versions of OnPaint) and try to change the labels Text to some path thats selected by the user using a path selection dialog, it simply displays it from left to right, in a way that when the path is too long for the size of the label, the right most part of the path isnt in view.

What am I doing wrong?
Should I set some properties of the label object?

Thanks for helping,
Ofer.
Ofer

View the full article
 
Back
Top