Link to home
Start Free TrialLog in
Avatar of Peter Kiers
Peter KiersFlag for Netherlands

asked on

Show a contextmenu when right-click on a selected node of a lisview.

Dear Experts,

I have set a contextmenu to a listview. But as you can see in the picture
I can right-click anywhere in the listview.

What I would like is to show the contextmenu only when a user right-clicks
on a selected node.

Who knows the answer?

Peter
Example.jpg
Avatar of kaufmed
kaufmed
Flag of United States of America image

I believe you could do something like this:  maintain a reference to the ContextMenu, but initially set the ListView's ContextMenu to null. Then, add a SelectedIndexChanged handler and check which mouse button was pressed--if the right button was pressed, assign the menu to to the ListView's ContextMenu property; otherwise, assign null. To check which button was pressed, you can keep a global MouseButtons variable that you assign in handlers for both the MouseDown and MouseUp events of the ListView.

Here is an example:
using System;
using System.Windows.Forms;

namespace _27375273
{
    public partial class Form1 : Form
    {
        MouseButtons button;
        ContextMenu menu;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            menu = new ContextMenu();
            menu.MenuItems.Add(new MenuItem("Copy", copyMenuItem_Click));
            menu.MenuItems.Add(new MenuItem("Paste", pasteMenuItem_Click));
        }

        private void copyMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Text copied.");
        }

        private void pasteMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Text pasted.");
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (button == MouseButtons.Right)
            {
                this.listView1.ContextMenu = menu;
            }
            else
            {
                this.listView1.ContextMenu = null;
            }
        }

        private void listView1_MouseDown(object sender, MouseEventArgs e)
        {
            button = e.Button;
        }

        private void listView1_MouseUp(object sender, MouseEventArgs e)
        {
            button = MouseButtons.None;
        }
    }
}

Open in new window

There's a small bug in the above code which does not clear the menu after a selection has been made and a subsequent non-item click occurs. I'm looking into it.
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Peter Kiers

ASKER

Thansk.