Add context menus to your Windows Forms program. Context menus should appear when your user right-clicks. Context menus react to their surroundings. For example, a Copy option should appear if text is selected. Associate different controls with different context menus.
First, here is how to create ContextMenu controls in your Windows Forms program. For the example, you may have a TextBox on the form, which you can name anything you want. I will call it textBox1 in this guide. Now, let's make the ContextMenu control.
Each Windows Forms control has a ContextMenuStrip property. The job of the Visual Studio Designer view is to allow us to visually set those properties. We can do this by following steps similar to those that follow here.
We need to make the context menu actually do something. First, let's make it perform a Copy on textBox1 when the user clicks on it. Go ahead and double click on your custom menu item, which will create an event handler that looks like this. In our example, we use the Copy method call.
private void copyToolStripMenuItem1_Click(object sender, EventArgs e)
{
// Here, add the copy command to the relevant control, such as...
textBox1.Copy(); // added manually
}First, click on the ContextMenu and then look at Properties pane on the right. Then click on the lightning bolt in Properties pane. Finally, scroll down to Opening and double-click to the right of Opening. You will see the following code appear.
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
// Runs before the user sees anything. A great place to set
// Enabled to true or false.
}We need to change the contents of the above event handler. Let's it to set the Copy menu item as Enabled when the selection is present, and disabled when there is no selection. Modify the above code to look like the following code.
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
// An elegant way to make the ContextMenu item always be Enabled
// when there is a selection, and always disabled when there isn't.
copyToolStripMenuItem1.Enabled = textBox1.SelectionLength > 0;
}What we have accomplished here is a way to disable the context menu's items depending on other factors in the UI. You won't need to manage the ToolStripMenuItem objects in any other way, other than the check for whether you want them in the Opening event. When text is selected, the Copy menu item is enabled.
ContextMenuStrip is a useful control and it can truly bring a higher level of interactivity to your Windows Forms programs. Finally, check out my article about StatusStrip, which is related and important for Windows Forms.