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

前端 未结 1 1196
长情又很酷
长情又很酷 2020-12-06 03:05

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:\

相关标签:
1条回答
  • 2020-12-06 03:57

    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);
      }
    }
    
    0 讨论(0)
提交回复
热议问题