Drawing in Visual Basic

Another useful class is the Font. You can set a font two ways:

  • Set the font property of the form at design time. This lets you make choices from the common dialog for selecting font, size, and style.
  • Declare an instance of the Font class in the code.

Example 1: Use the properties of the form

In the design window, select a Font and ForeColor for the form. Write the code to draw the words when you click:

Public Class Form1
    Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
        Dim MyBrush As New SolidBrush(Me.ForeColor)
        Me.CreateGraphics.DrawString("Hello", Me.Font, MyBrush, e.X, e.Y)
    End Sub
End Class

Example 2: Declare the values in the code

Public Class Form1
    Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
        Dim MyBrush As New SolidBrush(Color.Red)
        Dim MyFont As New Font("Courier New", 12, FontStyle.Bold)
        Me.CreateGraphics.DrawString("Hello", MyFont, MyBrush, e.X, e.Y)
    End Sub
End Class
Experiment: Duplicate the program shown in the illustration.

NEXT: Numbered Dots Project