2013-10-01 42 views
0

如何才能在form_load代碼完成之前阻止我的應用程序不顯示?由於form_load代碼阻止應用程序不顯示

public partial class updater : Form 
{ 
    public updater() 
    {   
     InitializeComponent(); 
     timer1.Interval = (10000) * (1); 
     progressBar1.Value = 0; 
     progressBar1.Maximum = 100; 
     progressBar1.Update(); 
     timer1.Start(); 
    } 

    private void updater_Load(object sender, EventArgs e) 
    {   
     WebClient webClient = new WebClient(); 
     webClient.DownloadProgressChanged += webClient_DownloadProgressChanged; 

     webClient.DownloadFile("http://download827.mediafire.com/jl9c098fnedg/ncqun56uddq0y1d/Stephen+Swartz+-+Survivor+%28Feat+Chloe+Angelides%29.wav", Application.StartupPath + "\\Stephen Swartz - Survivor (Feat Chloe Angelides).wav"); 
     // System.Diagnostics.Process.Start("\\Test.exe"); 
     this.Close(); 
    } 
    void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
    { 
     progressBar1.Value = e.ProgressPercentage; 
     progressBar1.Update(); 
    } 
} 
+0

使用'Shown'事件而不是'Load'事件。 –

+6

請重申沒有雙重否定的問題。不知道你想在這裏完成什麼。 –

回答

1

一種方法是從加載Shown Event移動您的代碼。所以代碼將在顯示錶單後開始運行。

另一個是創建thread,您將在其中下載文件。 爲了這個目的,你可以使用BackgroundWorker

private void updater_Load(object sender, EventArgs e) 
{  
    BackgroundWorker worker = new BackgroundWorker(); 
    worker.DoWork += (s, eArgs) => 
     { 
      WebClient webClient = new WebClient(); 
      webClient.DownloadFile("someUrl", "somePath"); 
     }; 
    worker.RunWorkerAsync(); 
} 

還存在webClient.DownloadFileAsync方法巫婆在這種情況下適合更好。你可以在sa_ddam213的答案中找到描述。

3

如果使用DownloadFileAsync它不會阻止用戶界面線程,將允許FormProgressbar加載和顯示進度,那麼你可以使用DownloadFileCompleted事件關閉Form

例子:

public Form1() 
    { 
     InitializeComponent(); 
     progressBar1.Value = 0; 
     progressBar1.Maximum = 100; 
     progressBar1.Update(); 
    } 

    private void updater_Load(object sender, EventArgs e) 
    { 
     WebClient webClient = new WebClient(); 
     webClient.DownloadProgressChanged += webClient_DownloadProgressChanged; 
     webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted); 
     webClient.DownloadFileAsync(new Uri("http://download827.mediafire.com/jl9c098fnedg/ncqun56uddq0y1d/Stephen+Swartz+-+Survivor+%28Feat+Chloe+Angelides%29.wav"), Application.StartupPath + "\\Stephen Swartz - Survivor (Feat Chloe Angelides).wav"); 
    } 

    private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) 
    { 
     Close(); 
    } 

    private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
    { 
     progressBar1.Value = e.ProgressPercentage; 
     progressBar1.Update(); 
    } 
+0

這個工程!我嘗試了form_show方法,但它不起作用,所以我決定嘗試這個方法!謝謝。 –

相關問題