C#中两个窗体将相互跳转

来源:互联网 发布:java jdk 1.7 mac下载 编辑:程序博客网 时间:2024/05/29 09:26


首先 program.cs 中

[STAThread]static void Main(){    Application.EnableVisualStyles();    Application.SetCompatibleTextRenderingDefault(false);    // 自动生成的代码是这样的    // Application.Run(new Form1());    // 表示 实例化一个新的 Form1 并显示之 此时程序进入消息循环    // 一旦 Form1 被关闭则程序也随之关闭了    // 为了让程序在 Form1 关闭后可以继续运行 需要修改下    new Form1().Show();    Application.Run();    // 这样做就能避免 Form1 被关闭后程序自动退出了    // 但这样做的风险是什么呢?    // 一旦用户忘记了 Application.Exit();    // 则程序在所有窗口关闭后 其进程仍然没有结束    // 所以 Application.Exit(); 这行代码是需要手动添加的}

Form1:Button_Click
Form2 f = new Form2();f.Show();this.Close();

Form2:Button_Click

Form1 f = new Form1();f.Show();this.Close();

注意:当最后一个窗口关闭时要调用 Application.Exit(); 否则程序进程是不会结束的


解决办法:(假设Form2是最后一个窗口)

private void Panel1_Click(object sender, EventArgs e){    Form2 f2 = new Form2();    f2.Closed += new EventHandler(this.f2_Closed);//f2.Closed += (obj, args) => { Application.Exit(); };    f2.Show();    this.Close();}private void f2_Closed(object sender, EventArgs e){    Application.Exit();}