Simply don't re-create the Form if it is already created; don't re-show the Form if it is already visible:
In Form scope:
Form1 f1 = new Form1();
Form2 f2 = new Form2();
Form3 f3 = new Form3();
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
switch(e.Node.Text)
{
case "Node1":
if(! f1.Visible) f1.Show();
break;
case "Node2":
if(! f2.Visible) f2.Show();
break;
case "Node3":
if(! f3.Visible) f3.Show();
break;
}
}
Note this code assumes the user
cannot close the instances of the secondary Forms. Here's how you might handle that:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
switch(e.Node.Text)
{
case "Node1":
if(f1.IsDisposed) f1 = new Form1();
if(! f1.Visible) f1.Show();
break;
case "Node2":
if(f2.IsDisposed) f2 = new Form2();
if(! f2.Visible) f2.Show();
break;
case "Node3":
if(f3.IsDisposed) f3 = new Form1();
if(! f3.Visible) f3.Show();
break;
}
}
There might be good reasons to not allow the user to close (permanently) a secondary Form: it's costly to re-instantiate Forms; you might lose data entered on the Forms (if you haven't preserved it).
If you want the user to have an easy way to "hide" a secondary Form without really "closing" it then try this:
private void Form1_Load(object sender, EventArgs e)
{
foreach(Form frm in new List<Form> {f1, f2, f3})
{
frm.FormClosing += frm_FormClosing;
frm.Show();
}
}
private void frm_FormClosing(object sender, FormClosingEventArgs e)
{
(sender as Form).Hide();
e.Cancel = true;
}
And now I'd like to tell you there's a better to handle this in general: use two "symmetric" Dictionaries of Types <TreeNode, Form> and <Form, TreeNode> to synchronize selection between the Forms and the TreeView Nodes. If you want to know how to do that: ask here.