Home > Software design >  How to select a ListView item with right click C#
How to select a ListView item with right click C#

Time:06-16

I made a ListView that displays images. I added a MouseDown event handler and inside I made that:

private void FooListView_MouseDown(object sender, MouseEventArgs e)         
{
   if (e.Button == MouseButtons.Right)
   {
       var focusedItem = ltView.FocusedItem;
       if (focusedItem != null && focusedItem.Bounds.Contains(e.Location))
           cmsIconMenu.Show(FooListView, e.Location);
       else
           MessageBox.Show("Vous n'avez sélectionné(e) aucune icône.");
   }
}

because it sucks to left-click and then right-click to save an image directly. Other applications do not have this problem. So I need to add some code to check if: the user right clicked on a ListView item, focus it and show a context menu.

I actually tried: to check a post that I lost the link but it doesn't do the job.

(Ask me if there is not enough details about my problem).

(It is French because it's a French version of my app)

CodePudding user response:

Ok, so the answer is the answer of Jimi. So the code for my case is

private void FooListView_MouseDown(object sender, MouseEventArgs e)
{
   if (e.Button == MouseButtons.Right)
   {
        var lv = sender as ListView; // [...]
        var item = lv.HitTest(e.Location).Item;
                
        if (item == null)
        {
            MessageBox.Show("Vous n'avez sélectionné(e) aucune icône."); //In English it's You haven't selected any icons (images).
        }
        else
        {
            lv.FocusedItem = item;
            cmsIconMenu.Show(lv, e.Location);
        }
    }
}

Thanks Jimi!

You can also replace the name of the method by another name but keep these params (parameters)!

  • Related