To do this you can use the property Openforms, which is a collection with open forms, follow an example of how to use:
using System.Windows.Forms;
public partial class frmPrincipal : Form
{
public frmPrincipal()
{
InitializeComponent();
}
private void FecharFormulariosFilhos()
{
// percorre todos os formulários abertos
for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
{
// se o formulário for filho
if (Application.OpenForms[i].IsMdiChild)
{
// fecha o formulário
Application.OpenForms[i].Close();
}
}
}
private void btnFilho1_Click(object sender, System.EventArgs e)
{
FecharFormulariosFilhos();
// cria a exibe o formulário filho
frmFilho1 frmFilho = new frmFilho1();
frmFilho.MdiParent = this;
frmFilho.Show();
}
private void btnFilho2_Click(object sender, System.EventArgs e)
{
FecharFormulariosFilhos();
// cria a exibe o formulário filho
frmFilho2 frmFilho = new frmFilho2();
frmFilho.MdiParent = this;
frmFilho.Show();
}
}
I used the property IsMdiChild as a parameter to check which forms should be closed, but you can use others, for example Name or Text.
Note: the frmPrincipal (parent form) is also in the collection.
The reason I used a for regressive and not a foreach or a for normal, it is because it would make an error, as discussed in this question Close all open Forms except the main menu in c#.
Brawling man helped a lot...!!
– Johnatan Licar
@Matthew, good answer
– Diego Farias
You helped me a lot. Thank you
– Fabio Aragão