我開發簡單的Windows窗體在C#Form1_Load的不叫(嘗試有一個BackgroundWorker)
我想說明一個GUI,然後在後臺啓動一些任務中的應用。我想在表單中使用文本標籤來顯示這些任務的進度。
Program.cs中是非常簡單的:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form mainForm = (new Form1());
Application.Run(mainForm);
}
對於標籤我用結合
partial class Form1 : INotifyPropertyChanged
{
public string Title
{
get { return _title; }
set
{
_title = value;
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Title"));
}
}
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this, "Title", true));
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(46, 17);
this.label1.TabIndex = 0;
this.label1.Text = "label1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(763, 255);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
private string _title = "xxgg";
private System.Windows.Forms.Label label1;
public event PropertyChangedEventHandler PropertyChanged;
然後我想運行一個後臺工作,但由於某種原因 Form1_Load方法沒有執行。
private void Form1_Load(object sender, System.EventArgs e)
{
System.Console.WriteLine("Form loaded");
var bw = new BackgroundWorker();
bw.DoWork += bw_DoWork;
bw.RunWorkerAsync(); //Start the worker
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
InfoText it = new InfoText();
FileMover fm = new FileMover(it);
foreach(string path in sourcePaths)
{
fm.MoveFrom(path);
this.Title = it.text;
}
}
正如你所看到的,我想在運行後臺工作時更新標題。
我的Form1_Load沒有被調用的原因是什麼?謝謝
編輯: 我加入BackgroundWorker的代碼在Form1類是這樣的:
public partial class Form1 : Form
{
BackgroundWorker bw;
public Form1()
{
InitializeComponent();
it = new InfoText();
bw = new BackgroundWorker();
bw.DoWork += bw_DoWork;
bw.WorkerReportsProgress = true;
bw.ProgressChanged += Bw_ProgressChanged;
bw.RunWorkerCompleted += Bw_RunWorkerCompleted;
bw.RunWorkerAsync(); //Start the worker
}
private void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("done");
this.Title = it.text;
}
private void Bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("progress changed " + e.ProgressPercentage);
this.Title = it.text;
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
FileMover fm = new FileMover(it);
foreach(string path in sourcePaths)
{
fm.MoveFrom(path);
bw.ReportProgress(1);
}
}
}
現在它正是我想要的。
因爲它沒有在任何地方的表格中註冊... – fabrosell
改寫它在OnLoad覆蓋。不要從DoWork方法訪問GUI元素。 – LarsTech
我的Form1_Load現在被稱爲@fabrosell,但標題沒有被更新。在OnLoad中寫入它意味着什麼? – rluks