How to close all forms I want in C #

1

Suppose I have 4 forms: form1 , form2 , form3 and form4 . Knowing that the form1 window will always open first and when I give .close() to form2 it, along with the others, should close. How do I achieve this? Remembering that% w / o% should remain open and that this is no more than an assumption for us to have a more general answer that will help more people.

    
asked by anonymous 04.06.2018 / 05:31

2 answers

1

You can create a control class to store all the menus that you are opening, where it will save the menu that was opened and what is its "parent" menu, for example:

public class MenusAbertos
{
  public Control Menu {get; set;}
  public string ClassePai {get; set;}
}

public class ListaMenusAbertos
{
  public list<MenusAbertos> Menus {get; set;}
}

Then every time before closing a menu, you search in this list if any of them is "child" of that menu you are closing and if you have children, you close them before and delete them from the list.

    
04.06.2018 / 14:00
1

At this point it is worth emphasizing how you call the other forms, so that it closes according to the order of the call, below I will quote an example that I use.

Before you call any form by the button_Click event, let's instantiate first at the beginning of our form, first let's simply call our form_2

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Abrindo_e_Fechando_Forms
{
    public partial class Form1 : Form
{
    public Form_2 MeuForm2 = null;
    public Form_3 MeuForm3 = null;
    public Form1()
    {
        InitializeComponent();
    }
    private void btn_abrir_form_2_Click(object sender, EventArgs e)
    {
        Form_2 Form2 = new Form_2();
        Form2.Show();
      }

     }
 }

Now let's do as with that, Form2 calls Form3, and when you click close on form2 it closes form 3

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Abrindo_e_Fechando_Forms
  {
      public partial class Form_2 : Form
   {
    public Form_3 MeuForm3 = new Form_3();

     public Form_2()
     {
          InitializeComponent();
     }

    private void btn_abrir_form_3_Click(object sender, EventArgs e)
    {   

        MeuForm3.Show();
    }

       private void btn_fechar_formAtual_e_aberto_Click(object sender, EventArgs e)
    {
        MeuForm3.Hide();
        this.Close();
    }


  }
}

As you can see I created a new instance of form3 on Form2

public Form_3 MeuForm3 = new Form_3();

In other words, by instantiating Form3 it becomes our object and we can manipulate it in the best possible way. I hope this has helped in some way!

Atte!

    
04.06.2018 / 23:26