0

I am using VS 2019.
The presented code should display an animated GIF each time the 'btn_Display' is clicked. If the image is disposed I've got an error at ImageAnimator.UpdateFrames() in PictureBox.Paint after the second click.

Public Class Form1

    Dim animatedImage As Bitmap
    Dim currentlyAnimating As Boolean = False
    Dim framecounter As Integer
    Dim framecount As Integer
    Dim framdim As Imaging.FrameDimension
    Dim gifFile As String

    Private Sub OnFrameChanged(ByVal o As Object, ByVal e As EventArgs)
        PictureBox1.Invalidate()
    End Sub

    Sub AnimateImage()
        If Not currentlyAnimating Then
            ImageAnimator.Animate(animatedImage, New EventHandler(AddressOf Me.OnFrameChanged))
            currentlyAnimating = True
        End If
    End Sub

    Private Sub PictureBox1_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
        If framecounter < framecount Then
            AnimateImage()
            ImageAnimator.UpdateFrames()
            e.Graphics.DrawImage(Me.animatedImage, New Point(0, 0))
            framecounter += 1
            Application.DoEvents()
        End If

    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        PictureBox1.SizeMode = PictureBoxSizeMode.AutoSize
        PictureBox1.Visible = False
        gifFile = "E:\1.gif"
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btn_Display.Click
        startGif(gifFile)
    End Sub


    Sub startGif(ByVal FlName As String)

        currentlyAnimating = False
        animatedImage = New Bitmap(FlName)
        framecounter = 0

        PictureBox1.Size = animatedImage.Size
        PictureBox1.Visible = True

        framdim = New Imaging.FrameDimension(animatedImage.FrameDimensionsList(0))
        framecount = animatedImage.GetFrameCount(framdim)

        WaitFor_eoAnimation()
        animatedImage.Dispose()  ' <----- 
        PictureBox1.Visible = False
    End Sub

    Private Sub WaitFor_eoAnimation()
        '  Wait for end of animation
        Do
            Application.DoEvents()
        Loop While framecounter < framecount 'currentlyAnimating
    End Sub

End Class

Thanks in advance ... Eitan

Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • Get the code here: [How to play a GIF animation to the last Frame, then stop the animation?](https://stackoverflow.com/a/67305196/7444103) -- Remove all `DoEvents()` stuff. – Jimi Feb 16 '22 at 14:59
  • Dispose destroys all resources for the image, if you need to reference the image again, you either need to create a new instance or you don’t dispose of it – Hursey Feb 16 '22 at 18:07
  • Thanks Idle_Mind. I have to dispose it, since otherwise the memory heap grows every time i re-display it. –  Feb 18 '22 at 09:10

0 Answers0