detect form open and close said form

3

I hope you can help me.

What I want to do is detect a form that is inside my project, once the form has been detected, close that form, to detect the form I want to close I use the following code

foreach (Form frm in Application.OpenForms)
                {
                    if (frm.GetType() == typeof(form_tabla))
                    {
                        MessageBox.Show("from abierto");
                        break;
                    }
                }

now once you see what I want to close it, I hope you can help me, thanks

    
asked by Daniel 14.07.2017 в 05:44
source

2 answers

1

To close the active form you can do it in this way.

//Almacena una instancia del formulario activo.
Form currentForm = Form.ActiveForm;

//Sierra el formulario
currentForm.Close();

If you want to close them all

Environment.Exit(1);

Anyway, if you want to do it by a loop, you must use this code.

FormCollection fc = Application.OpenForms;

foreach (Form frm in fc)
{
    //código aquí... 
    frm.Close();
} 

I do not recommend this method, unless you want to do something else, apart from closing open forms.

You can see more information in the microsoft documentation .

I hope you have been useful.

    
answered by 14.07.2017 / 06:41
source
2

If in frm you find the form you are looking for correctly, simply do frm.Close() :

foreach (Form frm in Application.OpenForms)
{
       if (frm.GetType() == typeof(form_tabla))
       {
             frm.Close();
             break;
       }
}

Another option is to use LINQ and you avoid the loop:

var frm=Application.OpenForms.OfType<form_tabla>().FirstOrDefault();
if (frm!=null) frm.Close();
    
answered by 14.07.2017 в 09:53