Reputation: 3
I would like get a little help from you. I am working on a diagram creator which can be called more than once. The diagram every time is different than the earlier version but I would like to use the same filename. The problem is that when I click on the button the program is showing the diagram form with the diagram in the picturebox but if the form is closed and I am clicking on the button again I have an error ("A generic error occurred in GDI+"). I think the mf.dispose() does not close the file and it opened. What do you think what is the problem, how can I solve it?
Main Form:
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
Diagram Class:
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
Upvotes: 0
Views: 190
Reputation: 80
You need to dispose Diagram_FORM.PictureBox1.Image
when you close Form Diagram_FORM
, otherwise exception will occur when you init Metafile
with same filename c:\temp\test.wmf
next time in method create_diagram()
of class Diagram
:
Dim mf As New Metafile(filename, hdc, bounds, MetafileFrameUnit.Pixel)
You can add the following code in your Diagram_FORM
Form to dispose it's PictureBox1.Image
when you close it.
Protected Overrides Sub OnFormClosed(e As FormClosedEventArgs)
If PictureBox1.Image IsNot Nothing Then
PictureBox1.Image.Dispose()
End If
MyBase.OnFormClosed(e)
End Sub
Upvotes: 1