Reputation: 1746
I have a window forms project, I have a login screen, a menu and a couple of other forms, I'm switching between them with:
this.Hide();
frm.FormClosed += new FormClosedEventHandler(subFormClosed);
frm.Show();
and the FormClosedEventHandler(subFormClosed);
private void subFormClosed(object sender, FormClosedEventArgs e)
{
this.Close();
}
So the aim of this is that when a subform is closed by the user to close this.
There is however a problem, I want to go back to the menu and the issue is that I have one of two possibilites, that I can see:
I can pass the menu form to the subForm by reference to then show it and hide the subform - this seems to be one really really kludgy way of doing it but it would work.
I can just open a new version of the menu form - this would lead to huge memory issues in overuse (more instances being created and then never destroyed until the program is closed, e.g. 30 menu forms sub forms)
I was trying to use the CloseReason to check if the sub form was closed by the user or if it was closed from code, however both the exit button and this.Close()
return CloseReason.UserClosing
. Hence I couldn't differentate between the two types of exiting.
So basically what I'm asking for is there a better way of doing this, I've read about MDI and SDI and I can't really work out which would be applicable, or if the kludgy option 1 is the best way of doing this.
Upvotes: 1
Views: 137
Reputation: 18051
Although the answer with the ShowDialog solution is a very good one, here is another way to do if for whatever reasons one does not want to use ShowDialog:
In the constructor of your menu form, use the FormClosed
and the Shown
events of your subforms this way:
subForm1.FormClosed += (s, e) => showMenu();
subForm1.Shown+= (s, e) => hideMenu();
subForm2.FormClosed += (s, e) => showMenu();
subForm2.Shown+= (s, e) => hideMenu();
...
void showMenu()
{
this.Show();
}
void hideMenu()
{
this.Hide();
}
Then you can use subForm1.Show() freely and close them the way you want: the events will be triggered accordingly.
Upvotes: 1
Reputation: 737
You can use ShowDialog and pass the menu page as the Owner. Something like this:
In Menu:
// on menu navigation button click
this.hide();
SubForm sub = new SubForm();
sub.ShowDialog(this); // open as a dialog with this form as the owner
In Sub Form:
// on subform's back button click or better, in the FormClosing event
this.Owner.show();
this.Close(); // this line is not needed if implemented in FormClosing event
Upvotes: 2