Master Toolbars and Menus with the New ToolStrip Control : Page 2

For years, developers have complained about the difficulties involved in creating professional toolbars, menus, and status bars, notably the lack of flexibility and extensibility in the controls. The flexible and extensible new ToolStrip control in the .NET 2.0 framework promises to solve those problems by changing the underlying model.

by Vishnu Prasad

Sep 22, 2004

Page 2 of 6

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.

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 ToolStripseven in places where you wouldn't typically find them, such as this File menu dropdown.

The ToolStripControlHost constructor used in the preceding snippet accepts a "Control" parameterthe 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.