PictureBox 使用 ImageAnimator 类来制作 GIF 图像的动画。其中有 Stop() 方法来停止动画。不幸的是,它没有公开您需要修改它的成员,您必须自己使用 ImageAnimator。
如果您不反对使用反射来绕过这些限制,那么您可以使用后门。这通常是一个相当糟糕的主意,但 Winforms 处于维护模式,PictureBox 再次更改的可能性非常接近于零。它看起来像这样:
using System.Reflection;
...
private static bool IsAnimating(PictureBox box) {
var fi = box.GetType().GetField("currentlyAnimating",
BindingFlags.NonPublic | BindingFlags.Instance);
return (bool)fi.GetValue(box);
}
private static void Animate(PictureBox box, bool enable) {
var anim = box.GetType().GetMethod("Animate",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(bool) }, null);
anim.Invoke(box, new object[] { enable });
}
此示例按钮的 Click 事件可靠地停止和启动动画:
private void button1_Click(object sender, EventArgs e) {
Animate(pictureBox1, !IsAnimating(pictureBox1));
}
如果您不喜欢这些类型的 hack,那么您可以自己使用 ImageAnimator。