Simple Problem With ListBoxes
-
i was wondering what the code was to invoke a click event to highlight the item in the listbox when you right click. Im just using this to pull up a context menu but i want the item to be selected. Simple solution i hope.
In VB.NET, something like this...
Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown Dim item As Integer For j As Integer = 1 To ListBox1.Items.Count Dim rect As System.Drawing.Rectangle = ListBox1.GetItemRectangle(j - 1) If rect.Contains(e.X, e.Y) Then item = j - 1 Exit For End If Next ListBox1.SelectedIndex = item End Sub
At least, it worked for me. And, you could test to see if it was the right-mouse button first, too. I had this sample working with a context menu assigned to the ListBox, as well. -
In VB.NET, something like this...
Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown Dim item As Integer For j As Integer = 1 To ListBox1.Items.Count Dim rect As System.Drawing.Rectangle = ListBox1.GetItemRectangle(j - 1) If rect.Contains(e.X, e.Y) Then item = j - 1 Exit For End If Next ListBox1.SelectedIndex = item End Sub
At least, it worked for me. And, you could test to see if it was the right-mouse button first, too. I had this sample working with a context menu assigned to the ListBox, as well. -
Thank you that worked great. Do you know what the code would be for a 6.0 App. I want to use this in some of my 6.0 applications.
Something like this -- though bear in mind this needs to be refined, as it will error out if there are less than
items
currently populated in the list, anditems
should be defined as the total number of list items the list is capable of displaying.Private Sub List1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim items As Integer
Dim averageHeight As Integer
items = 14
averageHeight = List1.Height / items
For i = 1 To items
If Y > (((i - 1) * averageHeight) + 1) And Y < (i * averageHeight) Then
List1.ListIndex = i - 1
End If
Next
If Button = 2 Then
Form1.PopupMenu rclOne
End If
End Sub