[c#] Adding a right click menu to an item

I have been searching for a while for a simple right-click menu for a single item. For example if I right-click on a picture I want a little menu to come up with my own labels: Add, Remove etc. If anyone could help I would be most greatful.

Thanks for looking.

Here is the completed code:

    ContextMenu cm = new ContextMenu();             
    cm.MenuItems.Add("Item 1", new EventHandler(Removepicture_Click));             
    cm.MenuItems.Add("Item 2", new EventHandler(Addpicture_Click));              
    pictureBox1.ContextMenu = cm; 

This question is related to c# winforms visual-studio menu right-click

The answer is


This is a comprehensive answer to this question. I have done this because this page is high on the Google search results and the answer does not go into enough detail. This post assumes that you are competent at using Visual Studio C# forms. This is based on VS2012.

  1. Start by simply dragging a ContextMenuStrip onto the form. It will just put it into the top left corner where you can add your menu items and rename it as you see fit.

  2. You will have to view code and enter in an event yourself on the form. Create a mouse down event for the item in question and then assign a right click event for it like so (I have called the ContextMenuStrip "rightClickMenuStrip"):

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
    switch (e.Button)
        {
            case MouseButtons.Right:
            {
                rightClickMenuStrip.Show(this, new Point(e.X, e.Y));//places the menu at the pointer position
            }
            break;
        }
    }
    
  3. Assign the event handler manually to the form.designer (you may need to add a "using" for System.Windows.Forms; You can just resolve it):

    this.pictureBox1.MouseDown += new MouseEventHandler(this.pictureBox1_MouseDown);
    
  4. All that is needed at this point is to simply double click each menu item and do the desired operations for each click event in the same way you would for any other button.

This is the basic code for this operation. You can obviously modify it to fit in with your coding practices.


Having just messed around with this, it's useful to kjnow that the e.X / e.Y points are relative to the control, so if (as I was) you are adding a context menu to a listview or something similar, you will want to adjust it with the form's origin. In the example below I've added 20 to the x/y so that the menu appears slightly to the right and under the cursor.

cmDelete.Show(this, new Point(e.X + ((Control)sender).Left+20, e.Y + ((Control)sender).Top+20));

If you are using Visual Studio, there is a GUI solution as well:

  1. From Toolbox add a ContextMenuStrip
  2. Select the context menu and add the right click items
  3. For each item set the click events to the corresponding functions
  4. Select the form / button / image / etc (any item) that the right click menu will be connected
  5. Set its ContextMenuStrip property to the menu you have created.

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to visual-studio

VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio? How to download Visual Studio Community Edition 2015 (not 2017) Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio Code pylint: Unable to import 'protorpc' Open the terminal in visual studio? Is Visual Studio Community a 30 day trial? How can I run NUnit tests in Visual Studio 2017? Visual Studio 2017: Display method references What is the hamburger menu icon called and the three vertical dots icon called? Changing text color of menu item in navigation drawer How to get selected value of a dropdown menu in ReactJS Android custom dropdown/popup menu Creating a Menu in Python How to make a 3-level collapsing menu in Bootstrap? how to set active class to nav menu from twitter bootstrap How to make jQuery UI nav menu horizontal? Twitter Bootstrap add active class to li Adding a right click menu to an item

Examples related to right-click

Adding a right click menu to an item How to add a custom right-click menu to a webpage? Java Mouse Event Right Click Making custom right-click context menus for my web-app How to disable mouse right click on a web page? Right click to select a row in a Datagridview and show a menu to delete it right click context menu for datagridview How to distinguish between left and right mouse click with jQuery