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;
Add a contextmenu to your form and then assign it in the control's properties under ContextMenuStrip. Hope this helps :).
Hope this helps:
ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Item 1");
cm.MenuItems.Add("Item 2");
pictureBox1.ContextMenu = cm;
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.
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.
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;
}
}
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);
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.
If you are using Visual Studio, there is a GUI solution as well:
- From Toolbox add a ContextMenuStrip
- Select the context menu and add the right click items
- For each item set the click events to the corresponding functions
- Select the form / button / image / etc (any item) that the right click menu will be connected
- Set its ContextMenuStrip property to the menu you have created.
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));