-3

I know how to switch form to form, but my problem is that when switching from Form B to Form A. It always create a new Instance of Form A.

How can I avoid this behaviour?

Felix D.
  • 4,811
  • 8
  • 38
  • 72
Binh Trong
  • 9
  • 1
  • 3

1 Answers1

-2

What you are looking for is called Singleton.

For a very basic approach you can take this:

public partial class Form1 : Form
{
    public static Form1 Instance { get; set; } //Create an Instance Object of your Window

    public Form1()
    {
        InitializeComponent();
    }

    //Your call to open the Window
    private void OpenForm2()
    {
        if (Form2.Instance == null)//Check if Form2 has already been created
        {
            //if not: go create a new one !
            Form2.Instance = new Form2();
        }
        //Instance of Form2 is already created => open that one            
        Form2.Instance.Show();            
    }
}

public partial class Form2 : Form
{
    public static Form2 Instance { get; set; }

    public Form2()
    {
        InitializeComponent();
    }
}
Felix D.
  • 4,811
  • 8
  • 38
  • 72