6.5 Find All MDI Child Forms


Problem

You need to find all the forms that are currently being displayed in a Multiple Document Interface application.

Solution

Iterate through the forms in the MdiChildren collection of the MDI parent.

Discussion

The .NET Framework includes two convenient shortcuts for managing MDI applications: the MdiChildren and the MdiParent properties of the Form class. You can investigate the MdiParent property of any MDI child to find the containing parent window. You can use the MdiChildren collection of the parent to find all the MDI child windows .

For example, consider the following example (shown in Figure 6.3), which displays simple child windows. Each child window includes a label with some date information, and a button. When the button is clicked, the event handler walks through all the child windows and displays the label text that each one contains. Each window also exposes the label text through a read- only property.

Here's the form code for the child window:

 public class MDIChild : System.Windows.Forms.Form {     private System.Windows.Forms.Button cmdShowAllWindows;     private System.Windows.Forms.Label label;     // (Designer code omitted.)     public string LabelText {              get {             return label.Text;         }     }     private void cmdShowAllWindows_Click(object sender, System.EventArgs e) {         // Walk through the collection of child windows.         foreach (Form frm in this.MdiParent.MdiChildren) {                      // Cast the generic Form to the expended derived class type.             MDIChild child = (MDIChild)frm;             MessageBox.Show(child.LabelText, frm.Text);         }     }     private void MDIChild_Load(object sender, System.EventArgs e){         label.Text = DateTime.Now.ToString();     } } 

Notice that when the code walks through the collection of child forms, it must convert the generic Form reference to the custom derived MDIChild form class so that it can use the LabelText property.

click to expand
Figure 6.3: Getting information from multiple MDI child windows.



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net