Skip to content

Instantly share code, notes, and snippets.

@light-traveller
Last active October 23, 2019 09:35
Show Gist options
  • Save light-traveller/2529fcf3b58a39bcb32f86de086e76b1 to your computer and use it in GitHub Desktop.
Save light-traveller/2529fcf3b58a39bcb32f86de086e76b1 to your computer and use it in GitHub Desktop.
Prevent an Animated GIF from Looping Forever in WinForms
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace Example
{
public partial class MyForm : Form
{
private Image _image;
private bool _animating;
private int _counter;
private int _allFrames;
public MyForm()
{
InitializeComponent();
_image = Properties.Resources.SampleGif;
pictureBox.Paint += pictureBox_Paint;
}
private void AnimateImage()
{
if(_counter < _allFrames)
{
if (!_animating)
{
ImageAnimator.Animate(_image, OnFrameChanged);
_animating = true;
}
}
else
{
ImageAnimator.StopAnimate(_image, OnFrameChanged);
}
}
private void OnFrameChanged(object sender, EventArgs e)
{
pictureBox.Invalidate();
}
private void pictureBox_Paint(object sender, PaintEventArgs e)
{
AnimateImage();
ImageAnimator.UpdateFrames();
e.Graphics.DrawImage(_image, Point.Empty);
_counter++;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
var dim = new FrameDimension(_image.FrameDimensionsList[0]);
_allFrames = _image.GetFrameCount(dim);
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (!e.Cancel)
{
CleanUp();
}
}
private void CleanUp()
{
if (_image != null)
{
if (_animating)
{
ImageAnimator.StopAnimate(_image, OnFrameChanged);
}
_animating = false;
_image.Dispose();
_image = null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment