Search code examples
c#mdichildmdiparent

Implement List<T> of Form, with EventHandler, as an MDI Child


I can't seem to get this working.

It errors at this code:

Window[0].MdiParent = this;

Main Form contains:

static List<frmWindow> Window = new List<frmWindow>();

Window.Add(new frmWindow("windowName", 0));
Window[0].MdiParent = this; // Errors here
Window[0].Show(); // If I omit the above, then it will attempt to show the screen,
// but freeze and not focus (like it freezes in initialization phase)

FrmWindow:

public frmWindow(string name, int id)
{
    InitializeComponent();
    Name = name;
    ID = id;
    //lblName.Text = name;
}

There is also an event handler I will need to use on the MDI form. I'm using other forms the exact same way, the only difference is, they aren't in a List<T>. Maybe there is an alternative?

Edit for stack:

   at System.Windows.Forms.Control.get_Handle()
   at System.Windows.Forms.Control.get_CreateThreadId()
   at System.Windows.Forms.Form.set_MdiParentInternal(Form value)
   at System.Windows.Forms.Form.set_MdiParent(Form value)
   at Matrix.Client.frmMain.JoinRoom(eventData e) in \frmMain.cs:line 418
   at Matrix.Client.frmMain.Matrix_MatrixToUIEvent(Object sender, eventData e) in \frmMain.cs:line 401
   at Matrix.Client.MatrixHolder.Matrix.ServerToMatrixEvent(Object sender, eventData e) in \Matrix.Client\Matrix.cs:line 214
   at Matrix.Client.Models.ServerModels.ServerModel.Server.<>c__DisplayClass30_0.<<_StageTwoReaderServer>b__0>d.MoveNext() in Client\Models\ServerModels\ServerModel.cs:line 223

Solution

  • I think your error could be here:

    this.IsMdiContainer = true;
    this.Text = "MDI Parent";
    

    then in this code: static List Window = new List();

    Window.Add(new frmWindow("windowName", 0));
    Window[0].MdiParent = this; // Errors here
    Window[0].Show(); // If I omit the above, then it will attempt to show the screen,
    // but freeze and not focus (like it freezes in initialization phase)
    

    Perhaps you intend to show the last created window, in that case :

    Window.Add(new frmWindow("windowName", 0));
    Window[^1].MdiParent = this; // Errors here
    Window[^1].Show(); 
    

    not sure what your constructor is doing; perhaps update the answer with more details if this doesn't help

    as per your comment, you mention a background thread then perhaps try this:

    // Assuming this code is in a Form or Control
    if (this.InvokeRequired)
    {
        this.Invoke(new MethodInvoker(() => 
        {
           Window.Add(new frmWindow("windowName", 0));
           Window[^1].MdiParent = this; // Errors here
           Window[^1].Show();
        }));
    }
    else
    {
        Window.Add(new frmWindow("windowName", 0));
        Window[^1].MdiParent = this; // Errors here
        Window[^1].Show();
    }