首页 > 解决方案 > VB.Net 元文件生成错误(“GDI+ 中发生一般错误”)

问题描述

我想从你那里得到一点帮助。我正在开发一个可以多次调用的图表创建器。每次的图表都与早期版本不同,但我想使用相同的文件名。问题是,当我单击按钮时,程序会在图片框中显示图表表单,但是如果表单已关闭并且我再次单击按钮,则会出现错误(“GDI+ 中发生一般错误” )。我认为 mf.dispose() 不会关闭文件并打开它。你认为是什么问题,我该如何解决?

主要形式:

Imports System.Runtime.InteropServices
Imports System.Drawing.Imaging

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Diagram.create_diagram()
        Diagram_FORM.PictureBox1.Image = New Metafile("c:\temp\test.wmf")
        Diagram_FORM.Show()
    End Sub

图表类:


Imports System.Runtime.InteropServices
Imports System.Drawing.Imaging

Class Diagram

Public Sub create_diagram()
        Dim diagram_width As Integer = 600
        Dim diagram_Height As Integer = 600
        Dim filename As String = "c:\temp\test.wmf"
        
        Dim gr As Graphics
        gr = Graphics.FromImage(New Bitmap(diagram_width, diagram_Height))

        ' Make a Graphics object so we can use its hDC as a reference.
        Dim hdc As IntPtr = gr.GetHdc


        ' Make the Metafile, using the reference hDC.
        Dim bounds As New RectangleF(0, 0, Diagram_WidthSize, Diagram_HeightSize)
        Dim mf As New Metafile(filename, hdc, bounds, MetafileFrameUnit.Pixel)

        gr.ReleaseHdc(hdc)

        ' Make a Graphics object and draw.
        gr = Graphics.FromImage(mf)
        gr.PageUnit = GraphicsUnit.Pixel
        gr.Clear(Color.White)

        draw_diagram_background(gr)
        draw_diagram_curve(gr)

        gr.Dispose()
        mf.Dispose()

    End Sub

Private Sub draw_diagram_background(Byval gr as Graphics)

     'some code

End Sub

Private Sub draw_diagram_curve(Byval gr as Graphics)

    'some code

End Sub

End Class

标签: vb.netgdi+metafile

解决方案


Diagram_FORM.PictureBox1.Image关闭 Form 时需要 dispose ,否则下次在类的方法中使用相同的文件名Diagram_FORM初始化时会出现异常:Metafilec:\temp\test.wmfcreate_diagram()Diagram

Dim mf As New Metafile(filename, hdc, bounds, MetafileFrameUnit.Pixel)

Diagram_FORM您可以在您的表单中添加以下代码,以便PictureBox1.Image在您关闭它时处理它。

Protected Overrides Sub OnFormClosed(e As FormClosedEventArgs)
    If PictureBox1.Image IsNot Nothing Then
        PictureBox1.Image.Dispose()
    End If
    MyBase.OnFormClosed(e)
End Sub

推荐阅读