Auto ellipsis, done __manually__ in C# using TextRenderer

Before starting off with this article, first we need to understand what AutoEllipsis means. Most of the control in C# will have a boolean property called AutoEllipsis. C#’s description goes this way:

// Summary:
// Gets or sets a value indicating whether the ellipsis character (...) appears
// at the right edge of the System.Windows.Forms.Label, denoting that the System.Windows.Forms.Label
// text ext
ends beyond the specified length of the System.Windows.Forms.Label.
//
// Returns:
// true if the additional label text is to be indicated by an ellipsis; otherwise,
// false. The default is false.

label with out ellipsis

Now if you have a label with “Some relatively big sentence in the label” as its text and if the width of the control is small than the width of the text (width of the text ?? i will come to that later …), AutoSize is set to false then this is how it appears in the run time.

If you enable AutoEllipsis of the label, then this is how it looks like.

If you want to have your own way of handling the AutoEllipsis, follow me.

  • Put a label in to your application and make it AutoSize property to false


System.Windows.Forms.Label myLabel = new System.Windows.Label();

myLabel.AutoSize = false;

myLabel.Size = new Size(43, 23); //Some arbitrary value for the size

myLabel.AutoEllipsis = false; //We are gonna do it our self

  • Handle the paint event of the label new


myLabel.Paint += new PaintEventHandler(OnLabelPaint);

  • In the paint event handler put the ellipsis using TextRenderer
private void OnLabelPaint(object theSender, PaintEventArgs theArgs)
{
     TextRenderer.DrawText(theArgs.Graphics, myLabel.Text, myLabel.Font, new Rectangle(0, 0,
myLabel.Width, myLabel.Height), myLabel.ForeColor, myLabel.BackColor,
TextFormatFlags.EndEllipsis);
}

The TextFormatFlags will specify how to visualise the text in the screen. If the value of this is EndEllipsis, then it will automatically put … at the end of the string if the string’s width is more than the width of the label.

  • The above snippet will get you a partial AutoEllipsed text. I mean the string will be ellipsed, yet you won’t be able to see the ToolTip. Lets add the tool tip.

System.WIndows.Forms.ToolTip myToolTip = new System.Windows.Forms.ToolTip();

  • Now in the OnLabelPaint add the following statement,

myToolTip.SetToolTip(myLabel, myLabel.Text);

  • Thats it. You have made your own AutoEllipsis now.

*I was talking about text’s width correct ?? Try to do TextRenderer.MeasureText(myLabel.Text, myLabel.Font); — You will get the width of the text in pixel.

Tags: , ,

Leave a comment