Open a form from another Form in a C # Panel

0

I'm doing a program with Visual Studio 2015, it's a Windows Form project with a pretty good UI design, which allows you to open a Form within a Panel without opening it in a new window. That causes me a problem, because for example, when I want to open a Form and inside it with a button open another Form , I can not find a way to do it, why can not hide or delete the father of the latter?

This is my code:

private void AbrirFormInPanel(object formHijo)
    {
        if (this.panelContenedor.Controls.Count > 0)
            this.panelContenedor.Controls.RemoveAt(0);
        Form fh = formHijo as Form;
        fh.TopLevel = false;
        fh.FormBorderStyle = FormBorderStyle.None;
        fh.Dock = DockStyle.Fill;
        this.panelContenedor.Controls.Add(fh);
        this.panelContenedor.Tag = fh;
        fh.Show();
    }
    
asked by Gaston 06.05.2018 в 17:37
source

1 answer

1

A few months ago I asked a similar question: How to know if a form is open in a panel? and with the answer it seems to me that you can get the result you want.

  

I quote the original answer by Asier Villanueva

You could create a generic method with restrictions so that the used type inherits from Form and has an empty constructor ( where T : Form, new() )

This way you can search within the Controls collection of the panel if there is any control of the specified type. If it exists, bring it to the front. If it does not exist, create a new instance and add it to the panel:

private void AbrirFormulario<T>() where T : Form, new()
{
    Form formulario = panel_contenedor.Controls.OfType<T>().FirstOrDefault();
    if (formulario!=null)
    {
        //Si la instancia esta minimizada la dejamos en su estado normal
        if (formulario.WindowState == FormWindowState.Minimized)
        {
            formulario.WindowState = FormWindowState.Normal;
        }
        //Si la instancia existe la pongo en primer plano
        formulario.BringToFront();
        return;
    }
    //Se abre el form
    formulario = new T();
    formulario.TopLevel = false;
    panel_contenedor.Controls.Add(formulario);
    panel_contenedor.Tag = formulario;
    formulario.Show();
}

This way to call it you would just have to do:

AbrirFormulario<FormularioX>();
    
answered by 07.05.2018 в 14:45