tags:

views:

37

answers:

2

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();
+4  A: 

You need to make two changes to your code:

  • Use Show instead of ShowDialog 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.

Mark Byers
@Mark, When I use Show(); my form2 freezes up. I am also able to still handle methods in my first form when ShowDialog is used. I'm not sure what's going on with that, but I'm sticking with it because that's whats working currently...
Soo
A: 

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 Disposed 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.

stakx