执行长进程时Windows窗体中的动画GIF
我在C#中开发了一个简单的Windows应用程序(MDI),它将数据从SQL导出到Excel。
我正在使用ClosedXML来成功实现这一目标。
执行该过程时,我想显示一个包含动画GIF图像的图片框。
我是初学者,不知道如何实现这一点,在完成该过程后会出现图片框。
我看到很多post说要使用我从未使用过的背景工作者或线程,并且发现很难实现。
我可以通过一步一步的解释说明。
我在执行代码之前和之后调用的两个函数。
private void Loading_On() { Cursor.Current = Cursors.WaitCursor; pictureBox2.Visible = true; groupBox1.Enabled = false; groupBox5.Enabled = false; groupBox6.Enabled = false; Cursor.Current = Cursors.Arrow; } private void Loading_Off() { Cursor.Current = Cursors.Arrow; pictureBox2.Visible = false; groupBox1.Enabled = true; groupBox5.Enabled = true; groupBox6.Enabled = true; Cursor.Current = Cursors.WaitCursor; }
添加BackgroundWorker并不困难
- 在设计师中打开表单
- 打开工具箱( ctrl + alt + X )
- 打开类别组件
- 拖动From上的Backgroundworker
你最终会得到这样的东西:
您现在可以切换到“属性”选项卡上的事件视图,并为DoWork和RunWorkerCompleted添加事件
以下代码介绍了这些事件,请注意DoWork
如何使用DowWorkEventArgs
Argument属性来检索RunWorkerAsync
提供的值。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { // start doing what ever needs to be done // get the argument from the EventArgs string comboboxValue = (string) e.Argument; // if Argument isn't string, this breaks // remember that this is NOT on the UI thread // do a lot of work here that takes forever System.Threading.Thread.Sleep(10000); // afer this the completed event is fired } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // this runs on the UI thread Loading_Off(); }
现在,您只需要启动后台作业,例如从按钮单击事件调用RunWorkerAsync
private void button1_Click(object sender, EventArgs e) { Loading_On(); backgroundWorker1.RunWorkerAsync(comboBox1.SelectedItem); // pass a string here }
完成! 您已成功为表单添加了后台工作程序。
实现这一目标的最佳方法是在异步任务中运行动画,但相应的一些限制是可以使用线程hibernate在Windows窗体上执行此操作。
例如:在你的构造函数中,
public partial class MainMenu : Form { private SplashScreen splash = new SplashScreen(); public MainMenu () { InitializeComponent(); Task.Factory.StartNew(() => { splash.ShowDialog(); }); Thread.Sleep(2000); }
在开始一个新线程之后放置线程hibernate是非常重要的,不要忘记你在这个线程上做的每个动作你需要调用,例如
void CloseSplash(EventArgs e) { Invoke(new MethodInvoker(() => { splash.Close(); })); }
现在你的gif应该工作了!