(For the purposes of this answer, Form1
and Form2
represent classes inheriting from Windows.Window
)
I would recommend one of the following approaches
Approach 1: Keeping Form2
alive and able to show again
In this case, you'll need to make an instance variable on Form1
:
private Form2 form2;
In your code to "switch" to Form2
, do this:
if(form2 == null)
{
form2 = new Form2();
DependencyPropertyDescriptor.FromProperty(Window.VisibilityProperty,
typeof(Window)).AddValueChanged(form2, Form2_VisibilityChanged);
}
Hide();
form2.Show();
Then add this function to Form1
:
private void Form2_VisiblityChanged(object sender, EventArgs e)
{
if(form2.Visility == Visibility.Hidden) Show();
}
Now all you need to do is call Hide();
within Form2
to have it switch back to Form1
.
Approach 2: Closing Form2
and opening a new instance each time
This is a bit easier, and more in line with what you have:
Form2 form2 = new Form2();
form2.Closed += Form2_Closed;
Hide();
form2.Show();
Similarly, add this function to Form1
:
private void Form2_Closed(object sender, EventArgs e)
{
Show();
}
Now, instead of calling Hide();
in Form2
, call Close();