To do this you can use the #, which is a collection with open forms, is 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 IsMdiChild
property as a parameter to check which forms should be closed, but you can use others, for example Name
or Text
.
Note: frmPrincipal
(parent form) is also in the collection.
The reason I have to use a for
fault, not a foreach
or a for
normal, is why I'd give it an error, as discussed in this question
25.12.2014 / 22:19