执行长进程时Windows窗体中的动画GIF

时间:2015-07-10 10:17:20

标签: c# picturebox animated-gif

我在C#中开发了一个简单的Windows应用程序(MDI),它将数据从SQL导出到Excel。

我正在使用ClosedXML成功实现这一目标。

执行该过程时,我想显示一个包含动画GIF图像的图片框。

我是一名初学者,并且不知道如何实现这一目标,该过程完成后会出现图片框。

我看到很多帖子说要使用我从未使用过的背景工作者或线程,并且发现很难实现。

我可以通过一步一步的解释说明。

我在执行代码之前和之后调用的两个函数。

        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;
    }

2 个答案:

答案 0 :(得分:8)

添加this tutorial

并不难
  • 在设计器中打开表单
  • 打开工具箱( ctrl + alt + X
  • 打开类别组件
  • 拖动From
  • 上的Backgroundworker

你最终会得到这样的结论:

  

winform with backgroundworker

您现在可以切换到“属性”标签上的事件视图,并添加BackgroundWorkerDoWork

的事件
  

event properties

以下代码介绍了这些事件,请注意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();
    }

现在您只需要启动后台作业,例如从按钮点击事件中调用RunWorkerCompleted

    private void button1_Click(object sender, EventArgs e)
    {
         Loading_On();
         backgroundWorker1.RunWorkerAsync(comboBox1.SelectedItem); // pass a string here
    }

完成!您已成功为表单添加了后台工作程序。

答案 1 :(得分:1)

实现这一目标的最佳方法是在异步任务中运行动画,但相应的一些限制是可以使用线程睡眠在Windows窗体上执行此操作。

例如:在你的构造函数中,

public partial class MainMenu : Form
{

    private SplashScreen splash = new SplashScreen();

    public MainMenu ()
    {
        InitializeComponent();

        Task.Factory.StartNew(() => {
            splash.ShowDialog();
        });

       Thread.Sleep(2000);
   }

在开始新线程之后放置线程休眠是非常重要的,不要忘记您在此线程上执行的每个操作都需要调用,例如

    void CloseSplash(EventArgs e)
    {
        Invoke(new MethodInvoker(() =>
        {
           splash.Close();
        }));
    }

现在你的gif应该可以工作了!