Multi Colored Text In Label In VB.Net

  • Thread starter Thread starter David William Smith
  • Start date Start date
D

David William Smith

Guest
Public Class Form1
' var for lable1 text
Private Label1Txt As String = String.Empty

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Do this here or in IDE at design time!
Label1.AutoSize = False ' disable labels autosize.
Label1.Text = String.Empty ' clear text in labels.
End Sub

' Test, Set Label1 text
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Label1Txt = "$480.00"
Label1.Refresh() ' redraw label
End Sub

' Test, Clear Label1 text
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Label1Txt = ""
Label1.Refresh() ' redraw label
End Sub

' Label1 paint event
Private Sub Label1_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Label1.Paint
DrawLabel(DirectCast(sender, Label), Label1Txt, e) ' Or just use label name, 'DrawLabel(Label1, Label1Txt, e)
End Sub

' Sub - Draw first char in red, remaining text in blue.
Private Sub DrawLabel(ByVal Lbl As Label, ByVal Txt As String, ByVal e As PaintEventArgs)
' if nothng to draw then just clear and return
If Txt.Length = 0 Then
e.Graphics.Clear(Lbl.BackColor)
Return
End If
Dim startPoint As New Point(0, 0)
Dim firstChar As String = Txt.Substring(0, 1)
Dim flags As TextFormatFlags = TextFormatFlags.NoPadding
' resize label to Txt size, + pad for borders (dirty workaround).
Lbl.Size = TextRenderer.MeasureText(e.Graphics, Txt & " ", Lbl.Font, New Size(Integer.MaxValue, Integer.MaxValue), flags)
' draw first char in red
TextRenderer.DrawText(e.Graphics, firstChar, Lbl.Font, startPoint, Color.Red, flags)
' do we have more text to draw?
If Txt.Substring(1).Length > 0 Then
' increment start point for remaining text (size of first char)
startPoint.X += TextRenderer.MeasureText(e.Graphics, firstChar, Lbl.Font, New Size(Integer.MaxValue, Integer.MaxValue), flags).Width
' draw remaining text in blue
TextRenderer.DrawText(e.Graphics, Txt.Substring(1), Lbl.Font, startPoint, Color.Blue, flags)
End If
End Sub
End Class



When i run the project, it does not show label.

I set break point and found that it goes to only form load even and button click event only.
It never goes to "Label1_Paint" and "DrawAmount"
Thanx

Continue reading...
 
Back
Top