How to use Context Menu Strip in C#
By FoxLearn 11/21/2024 1:21:53 PM 4.99K
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 make an Alarm clock in C#
- How to Load selected columns data in DataGridView in C#
- How to Save and Retrieve Image from SQL database in C#
- How to use BindingSource and BindingNavigator in C#
- How to insert Math Equation in RichTextBox in C#
- How to Transfer Information between Forms in C#
- How to Encrypt and Decrypt a String in C#
- How to Live Currency Converter in C#