C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Start: Here we show how to create ContextMenuStrip controls in your Windows Forms program.
TextBox: For the example, you may have a TextBox on the form, which you can name anything you want. We will call it textBox1 in this guide.
Then: Double-click on the ContextMenuStrip item and then enter some text such as "Copy" in the gray box in the context menu.
Next: Go ahead and double click on your custom menu item, which will create an event handler that looks like this.
Code that implements Click event: C#
private void copyToolStripMenuItem1_Click(object sender, EventArgs e)
{
// Here, add the copy command to the relevant control, such as...
textBox1.Copy(); // Added manually.
}
Finally: Scroll down to Opening and double-click in the user interface to the right of Opening.
And: You will see this block of code appear. It is generated by the Visual Studio environment.
Code that implements Opening event: C#
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
// Runs before the user sees anything.
// A great place to set Enabled to true or false.
}
More detailed opening event handler: C#
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;
}