Zebra0.com

visual-basic listmanager2

In the menu, we have both print and print preview. Both of these will need to set up the page using graphics methods.

From the toolbox add a PrintDialog printdialog, a PrintDocument PrintDocument, and a PrintPreviewDialog PrintPreviewDialog. (We are not using the PrintDialogControl.)
These controls will all appear below the form. (They are not visible at run time.)

Double Click on PrintDialog1 and add the code shown below.

Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
  'Setup the document for print or print preview
  Dim page As Graphics = e.Graphics  'the page will be drawn on the page
  Dim xpos As Integer = 50 '50 pixel margin on left
  Dim ypos As Integer = 80 '80 pixel margin at top
  'We must assign temporary values when we create a New instance of Font
  Dim myFont As New Font("Arial", 12, FontStyle.Regular) 'We override these in the next line
  myFont = FontDialog1.Font  'Use the same font that was selected for the list box
  Dim myBrush As New SolidBrush(Me.ListBox1.ForeColor) 'Use the color of the font in the list box
  page.DrawString(currentFile, myFont, myBrush, xpos, ypos) 'draw the name of the file
  ypos = ypos + myFont.Unit * 10 'move down the y position before drawing the next line
  Dim i As Integer
  For i = 0 To ListBox1.Items.Count - 1 'each item in the list box
    page.DrawString(ListBox1.Items(i), myFont, myBrush, xpos, ypos)
    ypos = ypos + myFont.Unit * 10  'move down the y position before drawing the next line
  Next
End Sub

Once we can "draw" the page in the PrintDocument, the rest is easy!

Double click on the menu item Print Preview and add the code below:

Private Sub mnuPrintPreview_Click(sender As Object, e As EventArgs) Handles mnuPrintPreview.Click
  Me.PrintPreviewDialog1.Document = PrintDocument1
  Me.PrintPreviewDialog1.ShowDialog()
End Sub

Double click on the menu item Print and add the code below:

Private Sub mnuPrint_Click(sender As Object, e As EventArgs) Handles mnuPrint.Click
  If PrintDialog1.ShowDialog() = DialogResult.OK Then 'They didn't cancel
    PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings 'set up the output
    PrintDocument1.Print() 'send to the printer 
  End If
End Sub

See the complete code at this point.

Run and test your application.

NEXT: Select a Font