我有一个表单(f1
),需要在打开另一个指令(f2
)之前运行一些指令,并且结束时必须关闭。我设置了program.cs
Application.Run(new f1());
并在f1结尾处写了
f2 f = new f2();
f.ShowDialog();
this.Close();
但它并没有关闭,只是在后台。
答案 0 :(得分:0)
一切都应该按照你的方式工作,但隐藏f1并以这种方式显示f2:
this.Hide();
var frm2 = new f2();
frm2.Closed += (sender, args) => this.Close();
frm2.Show();
提供更详细的答案:
public class Form1() : Form
{
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
var worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.RunWorkerAsync();
}
private void worker_DoWork(object sender, DoWorkEventArgs e) {
Thread.Sleep(5000);
// this is where you can load your data from file
}
private void worker_RunWorkerCompleted(
object sender, RunWorkerCompletedEventArgs e)
{
this.Hide();
var frm2 = new Form2();
frm2.Closed += (s, a) => this.Close();
frm2.Show();
}
}
因此Form1
将开始使用后台工作程序加载数据。加载数据后,BackgroundWorker
将触发RunWorkerCompleted
事件。该事件处理程序将隐藏Form1
而不是关闭它,创建Form2
,为form2的Closed
事件添加处理程序,以便关闭Form2
将停止您的应用程序,然后显示{ {1}}。