Share via


Bind all Fonts by Name with their Font Style to the ComboBox using VB.NET

Steps:

  1. Create a new project in Microsoft Visual Studio (File -> New -> Project -> Visual Basic -> Windows Application).
  2. Add a windows form named Form1. Insert a ComboBox control (ComboBox1).

Code:

Write the function 'BindComboBox' for binding all font names in the combobox control.

Private Sub  BindComboBox()
        ComboBox1.DrawMode = DrawMode.OwnerDrawFixed
        ComboBox1.Font = New  Font("Microsoft Sans Serif, 11.25pt", 11.25)
        ComboBox1.ItemHeight = 20
        Dim objFontFamily As FontFamily
        Dim objFontCollection As System.Drawing.Text.FontCollection
        Dim tempFont As Font
        objFontCollection = New  System.Drawing.Text.InstalledFontCollection()
        For Each  objFontFamily In  objFontCollection.Families
            If objFontFamily.IsStyleAvailable(FontStyle.Regular)  Then
                tempFont = New  Font(objFontFamily, 14, FontStyle.Regular)
            ElseIf objFontFamily.IsStyleAvailable(FontStyle.Bold)  Then
                tempFont = New  Font(objFontFamily, 14, FontStyle.Bold)
            ElseIf objFontFamily.IsStyleAvailable(FontStyle.Italic)  Then
                tempFont = New  Font(objFontFamily, 14, FontStyle.Italic)
            End If
            Dim lst As New  ListViewItem
            lst.Font = tempFont
            lst.Text = tempFont.FontFamily.Name
            ComboBox1.Items.Add(tempFont)
        Next
    End Sub

Add the code on the ComboBox_DrawItem event:

Private Sub  ComboBox1_DrawItem(ByVal sender As System.Object, _
                                   ByVal e As System.Windows.Forms.DrawItemEventArgs) _
                                   Handles ComboBox1.DrawItem
        e.DrawBackground()
        If (e.State And DrawItemState.Focus) <> 0 Then
            e.DrawFocusRectangle()
        End If
        Dim objBrush As Brush = Nothing
  
        Try
            objBrush = New  SolidBrush(e.ForeColor)
            e.Graphics.DrawString(DirectCast(ComboBox1.Items(e.Index), Font).Name, DirectCast(ComboBox1.Items(e.Index), Font), objBrush, e.Bounds)
        Finally
            If objBrush IsNot Nothing Then
                objBrush.Dispose()
            End If
            objBrush = Nothing
        End Try
    End Sub

Try your self!