Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WinForms - Smart TextBox Control to auto-Format Path length based on Textbox width

Does a smart textbox control (WinForms) exists that can display a path depending on the textbox width. For example, if the path is short it will display the entire path (C:\myfile.txt), but if the path is long it will display the start and end (C:\SomeFolder...\foo\MyFile.txt). The length of the characters displayed should be calculated (dynamically) by the textbox using its width. Any commercial or open source suggestions are welcome. Thank you very much.

like image 581
Joe Avatar asked Mar 07 '10 20:03

Joe


1 Answers

Yes, it's a built-in capability of the TextRenderer.DrawText() method. One of its overloads accepts a TextFormatFlags argument, you can pass TextFormatFlags.PathEllipsis. Doing this for a TextBox is not appropriate, the user cannot reasonably edit such an abbreviated path, you would have no idea what the original path might be. A Label is the best control.

Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. Don't make it too small.

using System;
using System.ComponentModel;
using System.Windows.Forms;

class PathLabel : Label {
  [Browsable(false)]
  public override bool AutoSize {
    get { return base.AutoSize; }
    set { base.AutoSize = false; }
  }
  protected override void OnPaint(PaintEventArgs e) {
    TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.PathEllipsis;
    TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, flags);
  }
}
like image 112
Hans Passant Avatar answered Nov 03 '22 21:11

Hans Passant