Liban
Liban

Reputation: 651

how to limit right click on selected listview item only or an item rather than empty spaces?

the right click in listview item is working but it work on every space in the listview, wether it is on item or empty spaces. i want to limit only to selected item.

i tried to use the listview1.HitTest but it is not working. still the right click is all the listveiw.

if (e.Button == MouseButtons.Right)
        {
            var loc = listView1.HitTest(e.Location);

            if (loc.Item != null && contextMenuStrip1.Items.Count == 0)
            {

                contextMenuStrip1.Items.Add("TEST1");
                contextMenuStrip1.Items.Add("TEST2");

            }              

        }

Upvotes: 2

Views: 1604

Answers (2)

Pere
Pere

Reputation: 1075

You can also still do the test inside listView1_mouseDown(); I did it this way and it's working fine, thus avoiding having to mess with ContextMenuOpening and Control.MousePosition. The only difference is that I declared lvhtias of ListViewHitTestInfo instead of var:

if (e.Button == MouseButtons.Right)
{
  ListViewHitTestInfo lvhti = this.listView1.HitTest(e.X, e.Y); // or e.Location
  if (lvhti.Item != null){
        contextMenuStrip1.Show(this.listView1, new Point(e.X, e.Y));
  }              
}

Upvotes: 2

okrumnow
okrumnow

Reputation: 2416

You may cancel the ContextMenuStrip.Opening event in case the HitTest shows that the mouse is not over an item.

You don't have the mouse position from the event args here, so you have to get it from Control.MousePosition

public void ContextMenuOpening(object sender, CancelEventArgs e) {

  Point mousePosition = myListView.PointToClient(Control.MousePosition);
  ListViewHitTestInfo hit = myListView.HitTest(mousePosition);

  e.Cancel = hit.Item == null;
}

Upvotes: 2

Related Questions