在WinForm中许多控件(本文以最常用的PictureBox为例)都有Image属性,如果该Image是一个动画Gif的话,它会自动运行动画。在某些场合,我们希望控制该动画的启停,此时我们首先想到了ImageAnimator,但实际使用时,我们发现以下指令根本不起作用,Gif停不下来,具体原因不明:
ImageAnimator.StopAnimate(box.Image,
new
EventHandler(OnImageAnimate));
private
void
OnImageAnimate(Object sender, EventArgs e)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
this.Invalidate();
}
此时,我想到控件的Enable属性,在其为false时,Gif是不会启动的,一旦设其为true,则动画立刻自动运行,因此只要该属性不作它用,则完全可以用来控制动画的启停。
需要注意的是线程的安全性,以下代码示例实现了某一控件点击后启动Gif运行5秒钟,然后停下来:
delegate
void
SetGifEnableCallback(Control control,
bool
enable);
![None.gif](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
void
picboxSearching_Click(
object
sender, EventArgs e)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
Thread t = new Thread(new ThreadStart(Animate));
t.Start();
}
![None.gif](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
private
void
SetGifEnable(Control control,
bool
enable)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
if (control.InvokeRequired)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
SetGifEnableCallback callback = new SetGifEnableCallback(SetGifEnable);
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
this.Invoke(callback, new object[]
{ control, enable });
}
else control.Enabled = enable;
}
![None.gif](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
private
void
Animate()
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
PictureBox box = this.pictureBox1;
AutoResetEvent waitHandler = new AutoResetEvent(false);
SetGifEnable(box, true);
waitHandler.WaitOne(5000, true);
SetGifEnable(box, false);
}