ListBox.IndexFromPoint Method (Point)
Returns the zero-based index of the item at the specified coordinates.
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)
Return ValueType: System.Int32
The zero-based index of the item found at the specified coordinates; returns ListBox.NoMatches if no match is found.
This method enables you to determine which item is located at a specific location within the control. You can use this method to determine which item within the list is selected when a user right-clicks the ListBox. The location of the cursor can be determined and passed to the p parameter of the method to determine which item the user right-clicked the mouse over. You can then display a shortcut menu to the user to provide tasks and features based on the specific item.
The following code example demonstrates how to perform drag-and-drop operations using a ListBox control that contains items to drop into a RichTextBox control. The constructor of the form sets the AllowDrop property to true to enable drag-and-drop operations to occur in the RichTextBox. The example uses the MouseDown event of the ListBox to start the drag operation by calling the DoDragDrop method. The example uses the DragEnter event to determine if an item being dragged into the RichTextBox is a valid data type. The DragDrop event performs the actual dropping of a dragged item into the RichTextBox control at the current cursor location within the RichTextBox. This example requires that the DragDrop and DragEnter events have been connected to the event handlers defined in the example.
Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() richTextBox1.AllowDrop = True End Sub Private Sub listBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles listBox1.MouseDown ' Determines which item was selected. Dim lb As ListBox = CType(sender, ListBox) Dim pt As New Point(e.X, e.Y) 'Retrieve the item at the specified location within the ListBox. Dim index As Integer = lb.IndexFromPoint(pt) ' Starts a drag-and-drop operation. If index >= 0 Then ' Retrieve the selected item text to drag into the RichTextBox. lb.DoDragDrop(lb.Items(index).ToString(), DragDropEffects.Copy) End If End Sub 'listBox1_MouseDown Private Sub richTextBox1_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) Handles richTextBox1.DragEnter ' If the data is text, copy the data to the RichTextBox control. If e.Data.GetDataPresent("Text") Then e.Effect = DragDropEffects.Copy End If End Sub 'richTextBox1_DragEnter Private Sub richTextBox1_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles richTextBox1.DragDrop ' Paste the text into the RichTextBox where at selection location. richTextBox1.SelectedText = e.Data.GetData("System.String", True).ToString() End Sub 'richTextBox1_DragDrop
Available since 1.1