快乐星期五! 我正在构建一个多WinForm应用程序,并且遇到了一些麻烦。
我有一个始终保持打开状态的主WinForm。它每分钟都会访问一个数据库,寻找变化,如果有变化,它将打开第二个WinForm(这看起来像是一种愚蠢的做事方式,但出于我的目的,这是最好的方法)。
将以下代码粘贴到我的Form1.cs中并不能解决问题:
Application.Run(new Form2());
你们能指出我正确的方向吗?我不知道在哪里转。
答案 0 :(得分:8)
Form2 form2 = new Form2();
form2.Show();
并且为了防止打开大量表格,可能:
Form2 form2 = new Form2();
form2.ShowDialog();
@comment:
BackgroundWorker
用于保持您的当前 UI线程响应。它的设计并不是为了保持多种形式的快节奏。请考虑在Background thread内将密集型代码作为ThreadPool
运行。
答案 1 :(得分:1)
如果您希望启动一个漫长的过程并向用户显示进度,例如就像您有进度条或类似的东西一样,您应该使用BackgroundWorker
来完成这项工作。这是一个简单的例子:
public partial class ProgressForm : Form {
// Assuming you have put all required controls on design...
// Allowing some properties to be exposed for progress update...
public properties MaximumProgress {
set {
progressBar1.Maximum = value;
}
public properties OverallProgress {
set {
progressBar1.Value = value;
}
}
public partial class MainForm : Form {
private BackgroundWorker backgroundWorker1;
private ProgressForm _pf;
public MainForm() {
InitializeComponent();
backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
// Assuming process starts on Button click.
private void button1_Click(object sender, EventArgs e) {
_pf = new ProgressForm();
_pf.MaximumProgress = number-of-elements-to-treat-returned-by-prevision-or-whatever-else;
// Launching the background workder thread.
backgroundWorker1.RunWorkerAsync(); // Triggering the DoWork event.
// Then showing the progress form.
_pf.ShowDialog();
}
private void backgroundWorker1_DoWork(object sender, EventArgs e) {
LaunchProcess();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) {
_pf.OverallProgress = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, EventArgs e) {
_pf.Close();
_pf.Dispose();
}
private void LaunchProcess() {
// Do some work here...
// Reporting progress somewhere within the processed task
backgroundWorker1.ReportProgress();
}
}
这不是一个可编译的代码,因为它的目的是说明主要的想法。
现在,你想做的事情是否相似?