Answers:
不太难。
要考虑的事项:
GIF动画:
如果您正在寻找GIF动画,可以生成它们:
另一种方法是:
我发现效果很好的另一种方法是在代码项目中找到的异步对话框控件
Application.DoEvents();
。可能的方法:部分完成某件事后,您的业务逻辑将触发一个事件,然后可以使用Application.DoEvents()
我有同样的问题。整个表单(包括gif)由于在后台长时间运行而停止重绘自身。这是我解决这个问题的方法。
private void MyThreadRoutine()
{
this.Invoke(this.ShowProgressGifDelegate);
//your long running process
System.Threading.Thread.Sleep(5000);
this.Invoke(this.HideProgressGifDelegate);
}
private void button1_Click(object sender, EventArgs e)
{
ThreadStart myThreadStart = new ThreadStart(MyThreadRoutine);
Thread myThread = new Thread(myThreadStart);
myThread.Start();
}
我只是创建了另一个线程来负责此操作。由于有了这种初始形式,所以可以继续重绘而不会出现问题(包括我的gif工作正常)。ShowProgressGifDelegate和HideProgressGifDelegate是将gif的pictureBox的可见属性设置为true / false的形式的委托。
请注意,在Windows中,传统上您不使用动画Gif,而是使用很少的AVI动画:有一个Windows本机控件仅用于显示它们。甚至还有将动画Gif转换为AVI的工具(反之亦然)。
System.Windows.Forms.PictureBox
控件支持,我将只使用动画GIF。
Public Class Form1
Private animatedimage As New Bitmap("C:\MyData\Search.gif")
Private currentlyanimating As Boolean = False
Private Sub OnFrameChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Invalidate()
End Sub
Private Sub AnimateImage()
If currentlyanimating = True Then
ImageAnimator.Animate(animatedimage, AddressOf Me.OnFrameChanged)
currentlyanimating = False
End If
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
AnimateImage()
ImageAnimator.UpdateFrames(animatedimage)
e.Graphics.DrawImage(animatedimage, New Point((Me.Width / 4) + 40, (Me.Height / 4) + 40))
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
BtnStop.Enabled = False
End Sub
Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStop.Click
currentlyanimating = False
ImageAnimator.StopAnimate(animatedimage, AddressOf Me.OnFrameChanged)
BtnStart.Enabled = True
BtnStop.Enabled = False
End Sub
Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click
currentlyanimating = True
AnimateImage()
BtnStart.Enabled = False
BtnStop.Enabled = True
End Sub
End Class
我遇到了同样的问题,并且通过实施曾经遇到过多个不同问题的解决方案遇到了不同的解决方案。最后,下面是我将来自不同职位的一些文章放在一起,它们按预期工作。
private void btnCompare_Click(object sender, EventArgs e)
{
ThreadStart threadStart = new ThreadStart(Execution);
Thread thread = new Thread(threadStart);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
这是Execution方法,该方法还包含调用PictureBox控件:
private void Execution()
{
btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = true; });
Application.DoEvents();
// Your main code comes here . . .
btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = false; });
}
请记住,PictureBox在“属性”窗口中不可见,或执行以下操作:
private void ComparerForm_Load(object sender, EventArgs e)
{
pictureBox1.Visible = false;
}