How to use Context Menu Strip in C#
By FoxLearn 2/17/2025 8:59:35 AM 5.58K
Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ContextMenuStripExample" and then click OK
Drag and drop a Button from Visual Toolbox onto your form designer, then design your form as shown below.
Context Menu Strip C# Sample
Next, Drag and drop a ContextMenuStrip
from the Toolbox to your form in the Visual Studio designer.
In the designer, click on the ContextMenuStrip
and use the "Edit Items" option to add menu items.
A ContextMenuStrip
in .NET (specifically in Windows Forms) is a type of menu that provides a list of options or actions when a user right-clicks on an object or area within a form or control.
The menu contains two options: Background and Foreground. Each is wired to its respective event handlers:
backgroundToolStripMenuItem_Click
foregroundToolStripMenuItem_Click
Add code to handle your form as shown below.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ContextMenuStripExample { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void backgroundToolStripMenuItem_Click(object sender, EventArgs e) { using(ColorDialog cd = new ColorDialog()) { if (cd.ShowDialog() == DialogResult.OK) btnMessage.BackColor = cd.Color; } } private void foregroundToolStripMenuItem_Click(object sender, EventArgs e) { //Open color dialog allows you to select color using (ColorDialog cd = new ColorDialog()) { if (cd.ShowDialog() == DialogResult.OK) btnMessage.ForeColor = cd.Color; } } } }
This example demonstrates how to use a ContextMenuStrip
to change the background and foreground colors of a button (btnMessage
) through a color dialog.
We will use a ColorDialog
that allows users to pick a color. It’s displayed using cd.ShowDialog()
. If the user clicks 'OK', the selected color is applied to the button's background or foreground.
VIDEO TUTORIAL
- How to use Error Provider in C#
- How to use Advanced Filter DataGridView in C#
- How to zoom an image in C#
- How to Use Form Load and Button click Event in C#
- How to Send and Receive email in Microsoft Outlook using C#
- How to update UI from another thread in C#
- How to Convert text to speech in C#
- How to Open and Show a PDF file in C#