28

I'm trying to make a list of items that you can do several actions with by right-clicking and having a context menu come up. I've completed that, no problem whatsoever.

But I'd like to have it so that when you right click on a item, instead of leaving the current item selected, to select the item the mouse is over.

I've researched this and other related questions, and I've tried to use indexFromPoint (which I found through my research) but whenever I right click on a item, it always just clears the selected item and doesn't show the context menu, as I have it set so that it wont appear if there is no selected item.

Here is the code I'm currently using:

ListBox.SelectedIndex = ListBox.IndexFromPoint(Cursor.Position.X, Cursor.Position.Y);
John Saunders
  • 160,644
  • 26
  • 247
  • 397

3 Answers3

45

Handle ListBox.MouseDown and select the item in there. Like this:

private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
    listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y);
}
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
demoncodemonkey
  • 11,730
  • 10
  • 61
  • 103
  • 4
    If context menu is already bounded to the listbox, just use: private void listBoxItems_MouseDown(object sender, MouseEventArgs e) { listBoxItems.SelectedIndex = listBoxItems.IndexFromPoint(e.X, e.Y); } – Rustam Irzaev Jan 13 '13 at 14:17
12

this one is working...

this.ListBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.List_RightClick);

private void List_RightClick(object sender, MouseEventArgs e)
{

    if (e.Button == MouseButtons.Right)
    {
        int index = this.listBox.IndexFromPoint(e.Location);
        if (index != ListBox.NoMatches)
        {
            listBox.Items[index];
        }
    }

}
Joel
  • 7,401
  • 4
  • 52
  • 58
Narottam Goyal
  • 3,534
  • 27
  • 26
  • 1
    Just replaced this line listBox.Items[index]; with .SelectedIndex = index; and this works perfectly. – Mr. B Dec 24 '14 at 19:35
  • 3
    Weird that the click event doesn't seem to capture the right button or the middle button. Have to use MouseUp to capture them.. – MattCochrane Nov 01 '15 at 01:57
0

Can also get same behaviour by setting a MouseRightButtonUp event on the whole listbox then:

private void AccountItemsT33_OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    // If have selected an item via left click, then do a right click, need to disable that initial selection
    AccountItemsT33.SelectedIndex = -1;
    VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), (sender as ListBox)).OfType<ListBoxItem>().First().IsSelected = true;
}
Dave Mateer
  • 6,588
  • 15
  • 76
  • 125