The title says it all: How can I close a different WinForm (B) from a different WinForm's (A) code?
I already have it set up so WinForm (B) gets opened in WinForm (A)'s code:
Form2 form2 = new Form2();
form2.ShowDialog();
The title says it all: How can I close a different WinForm (B) from a different WinForm's (A) code?
I already have it set up so WinForm (B) gets opened in WinForm (A)'s code:
Form2 form2 = new Form2();
form2.ShowDialog();
You need to make two changes to your code:
Show
instead of ShowDialog
so that the first window can still handle events.Here's some example code:
Form2 form2;
private void button1_Click(object sender, EventArgs e)
{
form2 = new Form2();
form2.Show();
}
private void button2_Click(object sender, EventArgs e)
{
form2.Close();
}
You will need to add some logic to make sure that you can't close a form before you have opened it, and that you don't try to close a form that you've already closed.
ShowDialog
will open form2
as a modal dialog, i.e. program execution won't continue until form2
is closed (either by the user, or in some of form2
's event handlers. It seems like you want to open form2
modeless, ie. call Show
instead. You should then be able to call form2.Close()
at any time.
Side note: Forms opened with Show
will auto-dispose once the user closes them. (On the other hand, modal forms, ie. those shown with ShowDialog()
, must be Dispose
d of manually.) That is, it may be possible that form2
is already disposed when you want to manually close it. I think calling Close
on a disposed form doesn't cause anything nasty to happen, I think it just calls Dispose
a second time.