打开另一个表单后如何关闭表单

时间:2016-01-15 15:12:46

标签: c# forms

所以,假设我点击了一个按钮,它应该打开一个新表单并关闭当前表单。

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
    Form2 AFormInstance = new Form2();
    AFormInstance.Show();
}

我尝试了this.Close()但最终发生的事情是两种形式都已关闭。如何打开Form2并关闭Form1

2 个答案:

答案 0 :(得分:0)

如果Button1的父级是Form1,您可以使用:

var formToBeClosed = ((sender as Button).Parent) as Form;
formToBeClosed.Close();

答案 1 :(得分:-2)

只需切换一些行:

private void button1_Click(object sender, EventArgs e)
{
    Form2 AFormInstance = new Form2();
    AFormInstance.Show();
    this.Close();
}

编辑:进一步思考:您不是不小心关闭了主表单吗?

将program.cs的默认代码更改为:

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Form1 form1 = new Form1();
        form1.Show();
        Application.Run();
    }

关闭应用程序使用:

Application.Exit();
相关问题