How to close a different WinForm from another's WinForm's code?
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 for开发者_如何学JAVAm2 = new Form2();
form2.ShowDialog();
You need to make two changes to your code:
- Use
Show
instead ofShowDialog
so that the first window can still handle events. - Keep a reference to the form you opened.
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.
Il you apply the "Show" method to a Winform, this one continues to listen to Windows messages, like WM_CLOSE. But if you use "ShowDialog", your winform becomes "deaf".
Just write form2.show(), and your winform will do whatever you want :-)
精彩评论