2015-07-10 78 views
1

我在C#中開發了一個簡單的Windows應用程序(MDI),它將數據從SQL導出到Excel。執行長進程時在Windows窗體中的GIF動畫

我正在使用ClosedXML來實現這一目標。

當執行過程時,我想顯示包含動畫GIF圖像的圖片框。

我是初學者,不知道如何做到這一點,圖片框出現後的過程完成。

我看到很多帖子說使用backgroundworker或線程,我從來沒有使用過,發現很難實現。

我可以有一個一步一步的例子與解釋。

我創建的兩個函數是我在執行代碼之前和之後調用的。

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

我已經使用線程成功顯示圖片框,但組框未禁用。 –

回答

7

這並不難添加BackgroundWorker

  • 在設計
  • 打開工具箱(CTRL + ALT + X
  • 打開表單打開類別組件
  • 拖動Ë的BackgroundWorker您從

你會最終了這樣的事情:

winform with backgroundworker

現在,您可以切換到屬性選項卡上的事件視圖,並添加事件對於DoWorkRunWorkerCompleted

event properties

下面的代碼都在這些事件中,注意如何DoWork使用DowWorkEventArgs參數屬性檢索在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 
    } 

完成!您已成功將背景工作人員添加到您的表單中。

1

實現這一目標的最好方法是在異步任務中運行動畫,但是相應的一些限制是可以在使用線程休眠的Windows窗體上執行該操作。

例如:在你的構造,

public partial class MainMenu : Form 
{ 

    private SplashScreen splash = new SplashScreen(); 

    public MainMenu() 
    { 
     InitializeComponent(); 

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

     Thread.Sleep(2000); 
    } 

把線程休眠後開始一個新的,不要忘記,每一個動作你做了這個主題,你需要調用OT這是非常重要的,例如

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

現在你的gif應該可以工作了!