Imports System.Drawing.Text
Public Class FontPractice
'members
Public fntFamilyName As String
Public fnt As Font
Private Sub FontPractice_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim installedFonts As New InstalledFontCollection()
Dim fntFamily As FontFamily
'go through the installed font collection and add each family to our combo box
For Each fntFamily In installedFonts.Families
fntFamilyName = fntFamily.Name
cboSelectFont.Items.Add(fntFamilyName)
Next
End Sub
'this function takes the font family we created and checks what style we can use
'it then returns the new font to be used
Public Function fntToUse(ByVal fontFamily) As Font
'check which styles are available for us to use with this font.
If fontFamily.IsStyleAvailable(FontStyle.Regular) Then
fntToUse = New Font(fntFamilyName, 10, FontStyle.Regular, GraphicsUnit.Point)
Else
If fontFamily.IsStyleAvailable(FontStyle.Bold) Then
fntToUse = New Font(fntFamilyName, 10, FontStyle.Bold, GraphicsUnit.Point)
Else
fntToUse = New Font(fntFamilyName, 10, FontStyle.Italic, GraphicsUnit.Point)
End If
End If
'return our font object
Return fntToUse
End Function
Private Sub cboSelectFont_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles cboSelectFont.DrawItem
'get the graphics object
Dim grfx As Graphics = e.Graphics
Dim fontFamily As FontFamily
If e.Index > -1 Then
'get the font family name of the current item
fntFamilyName = cboSelectFont.Items(e.Index)
fontFamily = New FontFamily(fntFamilyName)
'call our function to check the styles of the font to make sure
'we don't try to use a style thats not supported
fnt = fntToUse(fontFamily)
End If
Try
'draw the item to the control, but catch any exceptions
grfx.DrawString(cboSelectFont.Items(e.Index), fnt, Brushes.Black, New RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height))
Catch ex As Exception
End Try
End Sub
Private Sub cboSelectFont_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboSelectFont.SelectedIndexChanged
Dim fnt As Font
Dim fontFamily As FontFamily
Dim fntName As String
'get the name of the font family selected
fntName = cboSelectFont.SelectedItem.ToString()
'create an instance of the font family class with the font name
fontFamily = New FontFamily(fntName)
'pass the fontfamily to the function and get our font back
fnt = fntToUse(fontFamily)
lblSample.Font = fnt
End Sub
End Class