How to use Context Menu Strip in C#
By FoxLearn 11/21/2024 1:21:53 PM 5.09K
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 Print Text in a Windows Form Application Using C#
- How to fill ComboBox and DataGridView automatically in C#
- How to Read text file and Sort list in C#
- How to pass ListView row data into another Form in C#
- How to read and write to text file in C#
- How to make a Countdown Timer in C#
- How to Display selected Row from DataGridView to TextBox in C#
- How to Get all Forms and Open Form with Form Name in C#