开发者

How do I detect if a System.Windows.Forms.Label with AutoEllipsis is actually displaying ellipsis?

I have a Windows Forms Application where I display some client data in a Label. I have set label.AutoEllipsis = true.

If the text is longer than the label, it looks like this:

Some Text
Some longe... // label.Text is actually "Some longer Text"
              // Full text is displayed in a tooltip

which is what I want.

But now I want to know if the label makes use of the AutoEllipsis feature at runtime. How do I achive that?

Solution

Thanks to max. Now I wa开发者_C百科s able to create a control that try to fit the whole text in one line. If someone is interested, here's the code:

Public Class AutosizeLabel
    Inherits System.Windows.Forms.Label

    Public Overrides Property Text() As String
        Get
            Return MyBase.Text
        End Get
        Set(ByVal value As String)
            MyBase.Text = value

            ResetFontToDefault()
            CheckFontsizeToBig()
        End Set
    End Property

    Public Overrides Property Font() As System.Drawing.Font
        Get
            Return MyBase.Font
        End Get
        Set(ByVal value As System.Drawing.Font)
            MyBase.Font = value

            currentFont = value

            CheckFontsizeToBig()
        End Set
    End Property


    Private currentFont As Font = Me.Font
    Private Sub CheckFontsizeToBig()

        If Me.PreferredWidth > Me.Width AndAlso Me.Font.SizeInPoints > 0.25! Then
            MyBase.Font = New Font(currentFont.FontFamily, Me.Font.SizeInPoints - 0.25!, currentFont.Style, currentFont.Unit)
            CheckFontsizeToBig()
        End If

    End Sub

    Private Sub ResetFontToDefault()
        MyBase.Font = currentFont
    End Sub

End Class

Could need some fine tuning (make the step size and the minimum value configurable with designer visible Properties) but it works pretty well for the moment.


private static bool IsShowingEllipsis(Label label)
{
    return label.PreferredWidth > label.Width;
}


In fact, your Lable could be multiline. In this case, label.PreferredWidth wouldn't help. But you can use:

    internal static bool IsElipsisShown(this Label @this)
    {
        Size sz = TextRenderer.MeasureText(@this.Text, @this.Font, @this.Size, TextFormatFlags.WordBreak);
        return (sz.Width > @this.Size.Width || sz.Height > @this.Size.Height);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜