Build a Basic Menu
You may want to
download the sample project for this article at this point so you can test things out as you read through the article, but here are the first steps involved..
- Create a new Windows application project and rename it to MDIForm.cs.
- Set the form's IsMDIContainer to true.
- Drag and drop a MenuStrip onto the form and rename it to mnuStrip.
- In the form's constructor, the following code snippet adds two MenuItems and sets their Text property to "File" and "New". Note the use of DropDownItems.Add to add a ToolStripItem type. The ToolStripMenuItem inherits from ToolStripDropDownItem, and its DropDownItems property returns the associated ToolStripItemCollection.
ToolStripMenuItem fileitem = new
ToolStripMenuItem();
fileitem.Text = "&File";
ToolStripMenuItem newitem = new
ToolStripMenuItem();
newitem.Text = "&New";
newitem.Click += delegate {
FirstForm f = new FirstForm();
f.MdiParent = this;
f.Show(); };
fileitem.DropDownItems.Add(newitem );
Note that the preceding code associates the
Click event of the new ToolStripItem with an anonymous method that opens up another form of type
FirstForm and sets its MDIParent.
The next snippet adds a MonthCalendar to the ToolStripControlHost. As mentioned in Table 1, the ToolStripControlHost is a ToolStripItem type used to host Windows Forms controls. Normally, you'd do something significant when the user selects a particular date, but for simplicity, the sample code just shows a MessageBox.
 | |
| Figure 2. Using MonthCalendar with a ToolStripControlHost: The ToolStripControlHost provides a container that lets you host standard controls within ToolStripseven in places where you wouldn't typically find them, such as this File menu dropdown. |
MonthCalendar calend = new MonthCalendar();
ToolStripControlHost host = new
ToolStripControlHost(calend );
calend.DateSelected += delegate(object sender,
DateRangeEventArgs e)
{ MessageBox.Show("You selected " +
e.Start.ToShortDateString());
};
fileitem.DropDownItems.Add(host);
mnuStrip.Items.Add(fileitem);
The ToolStripControlHost constructor used in the preceding snippet accepts a "Control" parameterthe control you want to host in the ToolStrip. Note that this article simply demonstrates hosting a control in the standard ToolStripControlHost implementation. For customized ToolStripItems, you should inherit and create a custom ToolStripControlHost implementation. You can override methods such as
OnSubscribeControlEvents to handle events raised by the hosted controls or wrap custom functionality within properties to enrich the hosted control. That's how Microsoft implements the provided ToolStripItem controls internally, such as ToolStripComboBox, ToolStripProgressBar, etc.
Figure 2 shows how the MonthCalendar control displays when you run the preceding code and click the File menu.