首页 > 解决方案 > Close Form 2 from Form 1 C#

问题描述

I'm trying to build an application with a form window that needs to open and close another form by pressing a button. I want the same button to be used to open and close the same window.

    private void button1_Click(object sender, EventArgs e)
    {
        //GameBoard gameBoard = new GameBoard(); is written outside the private void as global variable.
        if (gameBoard == open)
        {
            gameBoard Close();
        }
        else
        {
            gameBoard.Show();
        }
    }

Thanks for any help.

标签: c#

解决方案


首先将表单引用设置为 null。

然后您可以执行以下操作:

    private GameBoard gameBoard = null;

    private void button1_Click(object sender, EventArgs e)
    {
        if (gameBoard == null || gameBoard.IsDisposed)
        {
            gameBoard = new GameBoard();
            gameBoard.Show();
        }
        else
        {
            gameBoard.Close();
            gameBoard = null;
        }
    }

推荐阅读