2011-10-11 21 views
2

我希望在執行功能時創建加載屏幕 - 就像在遊戲,新窗口或某些圖形中加載屏幕一樣。如何使執行功能期間的應用程序加載屏幕

所以我按下按鈕「開始」 - 應用程序啓動做一些東西,childform窗口顯示圖形 - 「進展中的功能,請稍候」

怎麼辦呢?

+2

看看在['BackgroundWorker'(HTTP:// msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx)控件。 –

回答

6

您可以依次在一個單獨的線程來執行你的功能使用BackgroundWorkerBackgroundWorker有很多功能支持您正在尋找的功能。如果你沒有使用另一個線程來執行你的函數,那麼主線程(UI線程)將會很忙,並且子窗口將無法正常工作。

backgroundWorker的一些關鍵注意事項。在另一個線程中進行DoWork,向主線程報告進度並取消異步進程是BackgroundWorker中最重要的功能。下面的例子很清楚地展示了這三個功能。但它顯示了任務完成的實際百分比。如果您只想顯示一條消息並使用Marquee style顯示ProgressBar,則不必切換WorkerReportsProgress標誌,也不需要ProgressChanged事件實施。

網絡上有很多示例可用。

using System; 
using System.Threading; 
using System.ComponentModel; 

class Program 
{ 
    static BackgroundWorker _bw; 

    static void Main() 
    { 
    _bw = new BackgroundWorker 
    { 
     WorkerReportsProgress = true, 
     WorkerSupportsCancellation = true 
    }; 
    _bw.DoWork += bw_DoWork; 
    _bw.ProgressChanged += bw_ProgressChanged; 
    _bw.RunWorkerCompleted += bw_RunWorkerCompleted; 

    _bw.RunWorkerAsync ("Hello to worker"); 

    Console.WriteLine ("Press Enter in the next 5 seconds to cancel"); 
    Console.ReadLine(); 
    if (_bw.IsBusy) _bw.CancelAsync(); 
    Console.ReadLine(); 
    } 

    static void bw_DoWork (object sender, DoWorkEventArgs e) 
    { 
    for (int i = 0; i <= 100; i += 20) 
    { 
     if (_bw.CancellationPending) { e.Cancel = true; return; } 
     _bw.ReportProgress (i); 
     Thread.Sleep (1000);  // Just for the demo... don't go sleeping 
    }       // for real in pooled threads! 

    e.Result = 123; // This gets passed to RunWorkerCompleted 
    } 

    static void bw_RunWorkerCompleted (object sender, 
            RunWorkerCompletedEventArgs e) 
    { 
    if (e.Cancelled) 
     Console.WriteLine ("You canceled!"); 
    else if (e.Error != null) 
     Console.WriteLine ("Worker exception: " + e.Error.ToString()); 
    else 
     Console.WriteLine ("Complete: " + e.Result);  // from DoWork 
    } 

    static void bw_ProgressChanged (object sender, 
            ProgressChangedEventArgs e) 
    { 
    Console.WriteLine ("Reached " + e.ProgressPercentage + "%"); 
    } 
} 

Reference

3

遊戲做這件事的方式是他們做兩個不同的應用程序。這不是一個真正的加載屏幕,而是更多的啓動器,檢查更新,顯示新聞並啓動遊戲。第二個應用是它自己的遊戲。如果你這樣做在C#中的發射器可以通過調用啓動遊戲:

System.Diagnostics.Process.Start("[APPLICATION_PATH]"); 
+1

它只是用於一些加載屏幕而不常用。第二個可執行文件更可能受DRM保護和/或加密,所以第一個可執行文件更像加載/解密程序。對於某些遊戲,它可能會檢查真實遊戲的先決條件(類似於安裝程序的不同引導程序)加載器可以用本地C++編寫,確保安裝遊戲的所有依賴關係(例如.net Framework或DirectX)。 – Mario

2

這是非常簡單的。您需要通過ShowDialog而不是Show來顯示此表單。並且在調用Hide之後的另一個線程中執行'some stuff'。這是第一個來我的腦海:

void DoSomeStuff() 
{ 
    //Showing splash screen 
    SplashForm.ShowDialog(this); 
    new Thread (()=> 
    { 
    //do stuff what you need 
    //Hiding splash screen 
    SplashForm.Invoke (new Action (SplashForm.Hide)); 
    }).Start(); 
} 

順便說一句,有超過9000的方式來做到這一點...)

相關問題