VB.NET•Use Event Handlers to Do the Extra Custom Work

Listing 1. Your print preview form becomes a second consumer of PrintDocument messages through the BeginPrint, PrintPage, and EndPrint events.

Private Sub InternalDoc_BeginPrint(...)
   ' ----- Clear any old values.
   TOCList.Items.Clear()
   TotalPages = 0
End Sub

Private Sub InternalDoc_PrintPage(...)
   ' ----- Advance to the next page.
   TotalPages += 1
End Sub

Private Sub InternalDoc_EndPrint(...)
   ' ----- Finished printing. Display the TOC.
   Dim scanTOC As System.Collections.IEnumerator
   Dim oneEntry As _
      PrintingTest.TableOfContentsEntry
   Dim tocDoc As PrintingTest.DocumentWithTOC

   ' ----- Show first page with auto-size.
   PageRange.Minimum = 1
   PageRange.Maximum = TotalPages
   ZoomDisplay(0.0)

   ' ----- Build the TOC if available.
   If (TypeOf InternalDoc Is PrintingTest. _
      DocumentWithTOC) Then
      ' ----- Scan through the TOC entries.
      tocDoc = CType(InternalDoc, _
         PrintingTest.DocumentWithTOC)
      scanTOC = tocDoc.TableOfContents. _
         GetEnumerator()
      Do While scanTOC.MoveNext()
         ' ----- Add this entry.
         oneEntry = CType(scanTOC.Current, _
            PrintingTest.TableOfContentsEntry)
         TOCList.Items.Add(oneEntry)
      Loop
   End If
End Sub