This is my first article, so please excuse the coarseness of it. The purpose of the program is to spring board the reader into (MDI) Multi Document Interfaces when they are accustomed to writing single document programs. Basically, this program just shows how to keep track of which form the user is working on so the "main menu" can operate correctly, which can also be extended to represent how the main form communicates with the child document forms.
The quick rundown is I fired up VS2005, with an empty project, created an MDI form, and created a variable to keep track of the document the user is working on. I then used the MDI child
Active event function to update my focus tracking variable. Don't worry if that last sentence was confusing. I have posted the code below, it is mostly straightforward and simple.
Using the Code
I would like to write some profound explanation, but the code below is pretty much what it is.
focusChild is a private global form variable, which gets assigned when the focus changes child forms.
private void MDIParent1_MdiChildActivate(object sender, EventArgs e)
focusChild = null;
foreach (Form childForm in this.MdiChildren)
focusChild = (txtForm)childForm;
childForm.Text += " Focused";
childForm.Text = childForm.Text.Remove(
The only other thing worth mentioning is what happens when the user clicks on an Open/Save button from the main menu. Below is the
Save event which uses the tracking variable and pulls from our custom form and saves it to a file.
private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
string FileName = saveFileDialog.FileName;
if (focusChild != null)
using (StreamWriter sw = new StreamWriter(FileName))
foreach (string line in focusChild.richTextBox1.Lines)
Points of Interest
It is worth noting that I use the
childForm.ContainsFocus property above for a reason.
ContainsFocus will return
true if the form or any of its components have focus.
form.focus will only return
true if the form itself has focus.
Just a down and dirty quick sample, no changes to date.