How to close another WinForm from another WinForm code?

How can I close another WinForm (B) from another WinForm (A) code?

I already configured it so that WinForm (B) opens in WinForm (A) code:

Form2 form2 = new Form2(); form2.ShowDialog(); 
+4
source share
3 answers

You need to make two changes to your code:

  • Use Show instead of ShowDialog so that the first window can still handle events.
  • Save the link to the open form.

Here is a sample 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 cannot close the form before you open it, and that you are not trying to close the form that you have already closed.

+5
source

ShowDialog will open form2 as a modal dialog box, that is, the program will not continue until form2 is closed (either by the user or by any of the form2 event handlers. To open form2 weak, i.e. call Show . Then you can call form2.Close() at any time.

Side note: Forms opened with Show are automatically deleted when the user closes them. (On the other hand, modal forms, i.e. those shown with ShowDialog() , must be Dispose d manually). That is, it is possible that form2 already configured when you want to manually close it. I think that calling Close on the arranged form does not cause anything unpleasant; I think that it just calls Dispose second time.

0
source

Il you apply the "Show" method to Winform, this one continues to listen to Windows messages such as WM_CLOSE. But if you use "ShowDialog", your winform becomes "deaf".

Just write form2.show () and your winform will do whatever you want :-)

0
source

Source: https://habr.com/ru/post/1311243/


All Articles