0

在 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();
    }
}
4

2 回答 2

3

如果您使用DownloadFileAsync它不会阻塞 UI 线程并允许Form加载并显示进度Progressbar,那么您可以使用该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();
    }
于 2013-10-01T23:38:58.590 回答
1

一种方法是从 Load Shown Event中移动代码。所以代码将在表单显示后开始运行。

另一个是创建一个线程,您将在其中下载文件。为此,您可以使用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 答案中找到描述。

于 2013-10-01T23:25:48.213 回答