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