Vb.net 使用PrintDocument和HasMorePages打印多页

Vb.net 使用PrintDocument和HasMorePages打印多页,vb.net,winforms,printdocument,Vb.net,Winforms,Printdocument,我正在尝试打印列表框中的项目列表。我有284件物品。其中大约四分之一被打印出来,其余的不打印,在底部最后一个条目是一半。我在网上读到关于使用e.HasMorePages跟踪你的结束位置并打印到下一页的文章,但是现在没有打印任何内容,它只是说它的打印页1、2、3、4、5……等等。什么也没发生。我必须按住ctrl+c键并关闭程序。如何实现所需的打印输出 Private Sub Print_Click(sender As Object, e As EventArgs) Handles Print.Cl

我正在尝试打印列表框中的项目列表。我有284件物品。其中大约四分之一被打印出来,其余的不打印,在底部最后一个条目是一半。我在网上读到关于使用e.HasMorePages跟踪你的结束位置并打印到下一页的文章,但是现在没有打印任何内容,它只是说它的打印页1、2、3、4、5……等等。什么也没发生。我必须按住ctrl+c键并关闭程序。如何实现所需的打印输出

Private Sub Print_Click(sender As Object, e As EventArgs) Handles Print.Click
  Dim PrintDialog1 As New PrintDialog
  Dim result As DialogResult = PrintDialog1.ShowDialog()
  If result = DialogResult.OK Then PrintDocument1.Print()

  ' PrintPreviewDialog1.Document = PrintDocument1
  ' PrintPreviewDialog1.ShowDialog()
End Sub

Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
  '  e.HasMorePages = True
  Dim itemCount As Integer
  Dim startX As Integer = 10
  Dim startY As Integer = 10
  Dim n As Integer
  For x As Integer = 0 To SoftwareLBox.Items.Count - 1
    e.Graphics.DrawString(SoftwareLBox.Items(x).ToString, SoftwareLBox.Font, Brushes.Black, startX, startY)
    startY += SoftwareLBox.ItemHeight
    If n = 150 Then
      e.HasMorePages = True
      n = 0
      startY = 10
    End If
    startY += e.PageBounds.Height
    n += 1
  Next
End Sub

您编写代码的方式告诉我您认为PrintPage方法只被调用一次,并且您正在使用这一次调用来打印所有内容。这不是它的工作方式

当需要打印新页面时,它将再次调用PrintPage方法,因此循环变量必须在PrintPage范围之外。下一页打印时,您需要知道当前打印的行号

试着这样做:

Private printLine As Integer = 0

Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs)
  Dim startX As Integer = e.MarginBounds.Left
  Dim startY As Integer = e.MarginBounds.Top
  Do While printLine < SoftwareLBox.Items.Count
    If startY + SoftwareLBox.ItemHeight > e.MarginBounds.Bottom Then
      e.HasMorePages = True
      Exit Do
    End If
    e.Graphics.DrawString(SoftwareLBox.Items(printLine).ToString, SoftwareLBox.Font, _
                          Brushes.Black, startX, startY)
    startY += SoftwareLBox.ItemHeight
    printLine += 1
  Loop
End Sub
打印前将printLine变量设置为零,或在BeginPrint事件中将其设置为零