dimanche 17 octobre 2021

How to dynamically create a form inside container using reflection?

I'm trying to create a generic library that is able to create one instance of a given Form. I'm using the WeifenLuo library.

In the main form, there is a dock container. If I create an instance directly in the method, it worked. However, when I call my generic method it shows the new Form outside the container.

private void button1_Click(object sender, EventArgs e)
        {
            // This works and put the new form inside the container
            Form1 form = new Form1();
            form.Show(mainFormDockPanel);
            // This just create the new form and open it outside the container
            //Forms.OpenForm<Form1, DockPanel>(this.mainFormDockPanel);
            Debug.WriteLine("Content: " + mainFormDockPanel.Contents.Count);
        }

Here is the generic function:

public static void OpenForm<T>(DockPanel dockPanel, T form = null, object obj = null, bool maximized = false) where T : class, new()
        {
            CreateMainForm();

            // Search for open forms
            foreach (DockContent frm in dockPanel).Contents)
            {
                // Verify if the content exists
                if (frm.GetType() == typeof(T) && obj == null)
                {
                    frm.Activate();
                    return;
                }
                // Check if the pressed button has a form
                if (obj != null && frm.GetType() == obj.GetType())
                {
                    frm.Activate();
                    return;
                }
            }

            if (form == null)
            {
                form = new T();
            }

            if (maximized)
                (form as DockContent).WindowState = FormWindowState.Maximized;

            Type type = typeof(T);
            MethodInfo methodInfo = type.GetMethod("Show", new Type[] { typeof(IWin32Window) });
            methodInfo.Invoke(form, new object[] { dockPanel });

            
        }

Do you guys realize what I'm missing?

Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire