0

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.

  • 1
    If you plan to reopen the same form instance then do not Close but Hide – Steve Mar 04 '19 at 21:25
  • You will have to run a check to see if the form is already open. [This question](https://stackoverflow.com/questions/3861602/how-to-check-if-a-windows-form-is-already-open-and-close-it-if-it-is) seems to have plenty of examples on how to do so. Write a separate method to run the check, and the assign `bool open` the return value (`true` or `false`) – Jaskier Mar 04 '19 at 21:25
  • 1
    check this [answer](https://stackoverflow.com/questions/14351925/open-windows-form-only-once-in-c-sharp) – NaDeR Star Mar 04 '19 at 21:28
  • Steve, If the window closes it does not matter if the same form instance reopens. – Ian Oberdorf Mar 04 '19 at 21:28

1 Answers1

0

Start off with your form reference set to null.

Then you can do something like:

    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;
        }
    }
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40