How to use Context Menu Strip in C#
By FoxLearn 11/21/2024 1:21:53 PM 5.2K
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.
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.
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 update UI from another thread in C#
- How to get CheckedListBox selected values in C#
- How to use Advanced Filter DataGridView in C#
- How to create a Notification Popup in C#
- How to Use Form Load and Button click Event in C#
- How to Link Chart /Graph with Database in C#
- How to Check SQL Server Connection in C#
- How to Generate Serial Key in C#