Jagadeesan
Jagadeesan

Reputation: 243

How can i know new MDI form added into parent MDI form?

I have created one parent form and raises the ControlAdded event for that. And also set the property IsMdiContainer to true for this parent form. And then if I create a new forms called ChildForm1 and ChildForm2 as like below code,

public partial class ParentForm : Form
{
  public ParentForm()
  {
    InitializeComponent();
    this.ControlAdded += Form1_ControlAdded;
    this.IsMdiContainer = true;

    Form ChildForm1 = new Form();           
    ChildForm1.MdiParent = this;
    ChildForm1.Show();

    Form ChildForm2 = new Form();       
    ChildForm2.MdiParent = this;
    ChildForm2.Show();
  }

  void Form1_ControlAdded(object sender, ControlEventArgs e)
  {
    MessageBox.Show("Control Added" + e.Control.Name);
  }
}

In this above code, when debug the code when adding child forms to parent forms it does not raises the ControlAdded event. So can you please suggest any way to achieve this?

Upvotes: 2

Views: 417

Answers (1)

Jagadeesan
Jagadeesan

Reputation: 243

I found the solution for this question. When marked the ParentForm as MdiContainer by setting the IsMdiContainer to true, the ParentForm.ControlAdded event raised for adding the "MdiClient" control to the parent form. So when adding MdiClient to parent MDI form, we can raise the ControlAdded event for the MdiClient control as like below,

  public ParentForm()
  {
    InitializeComponent();
    this.ControlAdded += Form1_ControlAdded;
    this.IsMdiContainer = true;

We need to raise the MdiClient.ControlAdded as like the below,

    void Form1_ControlAdded(object sender, ControlEventArgs e)
      {
           if(e.Control is MdiClient)
                e.Control.ControlAdded += MdiClient_ControlAdded;
      }

By default the MDI Child forms are added into the controls collection of the MdiClient in Parent form. So when set the ChildForm.MdiParent value as Parent form, the ControlAdded event for the MdiClient will raise.

void MdiClient_ControlAdded(object sender, ControlEventArgs e)
{

}

So by using the above method, we can know the child MDI forms added into the parent MDI forms.

Upvotes: 2

Related Questions