Select an item in a ListBox control (WinForm & C #) in the MouseDown event

In the ListBox control for Windows Forms, if I set ContextMenuStrip to display in the MouseDown event on the element, ContextMenuStrip will be shown, but the element that I click on the right button will not be selected. Elements can only be selected when I press the left button.

In the DataGrid view, I can fix this using the HitTest () method to check which item is in the current location, then select it and then display ContextMenuStrip. but unfortunately there is no HitTest method in the ListBox.

Is there any way?

+6
source share
1 answer

You can use the IndexFromPoint method:

 private void listBox1_MouseDown(object sender, MouseEventArgs e) { int index = listBox1.IndexFromPoint(e.Location); listBox1.SelectedIndex = index; } 
+7
source

Source: https://habr.com/ru/post/901672/


All Articles