Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right Click to select items in a ListBox

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);

2 Answers

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);
}
like image 166
demoncodemonkey Avatar answered Sep 09 '25 23:09

demoncodemonkey


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];
        }
    }

}
like image 21
Narottam Goyal Avatar answered Sep 10 '25 00:09

Narottam Goyal