How to use Context Menu Strip in C#

By FoxLearn 11/21/2024 1:21:53 PM   4.99K
In a Windows Forms application in C#, a ContextMenuStrip is used to create context menus that appear when you right-click on a control or form.

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.

contextmenustrip c#

Next, Drag and drop a ContextMenuStrip from the Toolbox to your form in the Visual Studio designer.

contextmenustrip in c#

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