views:

1946

answers:

2

okay, so i have listBox1, and its populated with items, id like to know how to 1. when you rightclick in the listbox, that the rightclicked item will be selected, 2. a rightclick menu will be displayed with several items.. 3. when you click on any of the items, a corresponding void will be triggered..

thanks in advance for any help, and code examples please!

A: 

First, you need to subscribe to ListBox.MouseClick event. You will be able do determine what button was pressed and cursor coordinates. Then, use ListBox.IndexFromPoint method to find clicked item. You can select it using ListBox.SelectedIndex property. To display context menu use ContextMenu or ContextMenuStrip classes. Additional documentation on context menu is available in MSDN

Rouslan Minasian
A MouseClick event will NOT be triggered by a context click on a ListBox.
BillW
+1  A: 

This feels to me like a "homework" question, so I am going to answer by (I hope) giving you just a few pointers to solving this for yourself.

Phase One

  1. create a sample project with a ListBox
  2. define event handlers for MouseClick, MouseDown, and Click events.
  3. put a Console.WriteLine("some appropriate text"); statement in each of those handlers so you can look in the Output Window in Visual Studio and see which event handler was called.

...

Phase Two

  1. run the test program and observe the difference between what events are reported for a left mouse down and a right-mouse down (assuming your environment has the context click set to the right mouse down ... which may not be true for everyone).

  2. focus on the one event you can intercept with a context-click.

  3. add a context menu to the test project and set that context menu to be the context menu of the ListBox.

  4. verify that you can now right click on an item in the ListBox and that the context menu will appear, BUT THE EVENT IS STILL HANDLED BY THE HANDLER YOU "DISCOVERED" IN STEP 2.

  5. now go through all the Event handlers for ListBox, and figure out which one could be used to detect, given a certain location in the ListBox, which List Item was "hit."

  6. once you can determine which List Item was right-clicked on, and you know your context menu is working, you have only the problem of making sure that the right-clicked List Item is selected : and that's pretty easy.

Figuring this out yourself will teach you several very useful things you'll be able to use later in programming to other controls.

best of luck, Bill

BillW