none
利用graphics打印出出错,无法访问已释放的对象! RRS feed

  • 问题

  • 试验出错前提:建立form1窗体,安放两个按钮,第一次按下button1可以正常预览和打印,第二次就提示出错,为什么?

    Public Class Form1
      Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        PrintDialog1.Document = PrintDocument1
        PrintDialog1.ShowDialog()
        Try
          PrintPreviewDialog1.Document = PrintDocument1
          PrintPreviewDialog1.Show()
          'PrintDocument1.Print()
        Catch ex As Exception
          MessageBox.Show("An error occurred while printing", ex.ToString())
        End Try
      End Sub
    
      ' Specifies what happens when the PrintPage event is raised.
      Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal ev As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        ev.Graphics.PageUnit = GraphicsUnit.Millimeter
        ' Draw a picture.
        'ev.Graphics.DrawImage(Image.FromFile(CurDir() & "\123.jpg"), ev.Graphics.VisibleClipBounds)
        '准备打印字符
        Dim mFont As New Font("宋体", 20)
        Dim mBrush As New SolidBrush(Color.Blue)
        ev.Graphics.DrawString("欢迎访问巧巧读书网", mFont, mBrush, 0, 0)
        ' Indicate that this is the last page to print.
        ev.HasMorePages = False
        ev.PageSettings.Margins.Left = 0
        ev.PageSettings.Margins.Top = 0
      End Sub
    
    End Class
    • 已编辑 fengqiwuyong 2010年11月30日 8:39 澄清问题
    2010年11月30日 3:44

答案

  • 终于找到原因了,是PrintPreviewDialog1.Show()
    在运行一次之后被释放了,需要重新加载。

    改正:

        Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
            PrintDialog1.Document = PrintDocument1
            PrintDialog1.ShowDialog()
            Try
                Dim PrintPreviewDialog2 As New PrintPreviewDialog
                PrintPreviewDialog2.Document = PrintDocument1
                PrintPreviewDialog2.Show()
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End Sub

    解决了

    2010年11月30日 9:45

全部回复

  • 直接在paint事件里用e.Graphics
    http://feiyun0112.cnblogs.com/
    2010年11月30日 3:57
    版主
  • 终于找到原因了,是PrintPreviewDialog1.Show()
    在运行一次之后被释放了,需要重新加载。

    改正:

        Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
            PrintDialog1.Document = PrintDocument1
            PrintDialog1.ShowDialog()
            Try
                Dim PrintPreviewDialog2 As New PrintPreviewDialog
                PrintPreviewDialog2.Document = PrintDocument1
                PrintPreviewDialog2.Show()
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End Sub

    解决了

    2010年11月30日 9:45