停止应用程序由于代码form_load而不显示
本文关键字:form load 显示 代码 应用程序 于代码 | 更新日期: 2023-09-27 18:33:41
如何阻止我的应用程序在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();
}
}
如果使用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();
}
一种方法是从加载显示事件中移动代码。因此,代码将在显示表单后开始运行。
另一个是创建一个线程,您将在其中下载文件。为此,您可以使用 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答案中找到描述。