Library code snippets

Output text to a form

In Visual Basic, the printer is not the only thing you can print to! You can also print text and graphics to a form or PictureBox. The code below gives you an example. The code could also be adapted to print the page using the printer too.

Option Explicit
'// you can change the font name, size and colour by changing the 
'// form's Font, FontSize and ForeColor properties.
Private Sub Form_Load()
    Call DrawText
End Sub
Private Sub DrawText()
    Dim strText As String
    Me.Cls '// clear form
    'Never allow the percentage to be 0 or 100 unless it is exactly that value. This
    'prevents, for instance, the status bar from reaching 100% until we are entirely done.
    strText = "Contents" '// set the text
    SetCenterPos (strText) '// set the center pos
    Me.Print strText '// print the text
    strText = ""
    SetCenterPos (strText)
    Me.Print strText
    strText = "Chapter 1: A walk in the woods"
    SetCenterPos (strText)
    Me.Print strText
    strText = "Chapter 2: The suprise"
    SetCenterPos (strText)
    Me.Print strText
End Sub
Private Sub SetCenterPos(strText As String)
    Dim intX As Integer
    Dim intWidth As Integer
    intWidth = Me.TextWidth(strText)
    '// Set intX to the starting location for printing the percentage
    intX = Me.ScaleWidth / 2 - intWidth / 2
    '// Go to the center print position
    Me.CurrentX = intX
End Sub

Comments

  1. 17 Jun 2003 at 12:25

    When using print to the form, remember to enable the AutoRedraw.
    If the code above doesn't work, this is likely to be the cause.

  2. 01 Jan 1999 at 00:00

    This thread is for discussions of Output text to a form.

Leave a comment

Sign in or Join us (it's free).