How to control MDI forms through a general method?

Asked

Viewed 93 times

1

I am developing a system with MDI forms. I have a menu that is the MdiParent and everyone else is allocated as your children.

Originally, MDI allowed me to open the same form several times; then I started to control the existence of the forms through a static statement, thus:

public static Form form1;

When opening the form:

if (form1 != null)
{
    form1.Activate();
}
else
{
    form1 = new TED_Dados();
    form1.MdiParent = this;
    form1.Show();
}

And finally, when I close the form:

Menu.form1 = null;

This code is functional, but it is necessary to replicate it to all forms, and I need all of them to be declared in the menu. I would like to know if there is any solution that would allow me to control all forms through a single class or method.

  • Menu is what? The parent form (MDI)?

  • Advice I give you to understand more about this: Create an MDI from the Visual Studio template, observe the code that is generated. You’ve got enough on your plate to work with Child of the MDI.

1 answer

1


There are several ways to solve this.

One approach I like is to create a generic method to open the Forms.

In this case, the method is in the MDI form.

public void OpenForm<TForm>() where TForm : Form, new()
{
    var form = Application.OpenForms.OfType<TForm>().FirstOrDefault();
    if (form != null)
        form.BringToFront();
    else
        new TForm {MdiParent = this}.Show();
}

See a working GIF:

inserir a descrição da imagem aqui

  • Excellent solution, thanks @LINQ! Still following this line, you can also pass parameters for a constructor through this method? I have a form that serves as registration and editing, and for the second case I need to pass an ID. I am passing a int? as a parameter for the function OpenForm but I could not differentiate the display of the new form for both cases.

  • @Caioposchardt There it will depend a little on your code structuring, if the parameters are always of the same type and such. There’s always something to do =D If you try to develop the solution for this new problem and can’t, open a new question so we can try to help you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.