Building Context Menus
In the very first code snippet in this article, clicking the New
menu opened a new form, which you haven't seen yet. You'll implement the ToolStrip, ContextMenuStrip and StatusStrip here.
Create the new Form and rename it to FirstForm
. Ensure that the code sets the new form's MDIParent
property before calling its Show
method. I've repeated the first code snippet below, for clarity.
ToolStripMenuItem fileitem = new
fileitem.Text = "&File";
ToolStripMenuItem newitem = new
newitem.Text = "&New";
newitem.Click += delegate
FirstForm f = new FirstForm();
f.MdiParent = this;
Drag and drop a ToolStrip onto the FirstForm form and rename it to tlStrip.
Also drag a ContextMenuStrip and rename it to cntxtMenu
Implement the Department and Sub-department items the same way as you did with the MenuStrip in the earlier examples, but this time, associate them with the ContextMenuStrip instead. The downloadable sample code
contains the complete implementation. Note that there's no difference between the MenuStrip and ContextMenuStrip implementation in terms of using the event model or the object model. This flexibility in the ToolStrip architecture helps you build reusable components/controls. Although this sample itself isn't generically reusable, it would be very easy to create an application configuration file that could implement this functionality.
|Figure 5: Child Form ToolStrip and ContextMenuStrip: The figure shows how the completed ToolStrip and ContextMenuStrip controls look in the child form.|
The ToolStrip implementation is very simple and uses a set of images in an ImageList. Figure 5
shows how the completed ToolStrip looks. Here's the code.
ToolStripButton lblQuest = new ToolStripButton();
lblQuest.Image = imgList.Images;
lblQuest.Text = "&Question";
lblQuest.Enabled = true;
ToolStripButton lblExcla = new ToolStripButton();
lblExcla.Image = imgList.Images;
lblExcla.Text = "&Exclamation";
lblExcla.Enabled = true;
ToolStripButton lblInfo = new ToolStripButton();
lblInfo.Image = imgList.Images;
lblInfo.Text = "&Information";
lblInfo.Enabled = true;
tlStrip.Raft = RaftingSides.Right;