ListBox.IndexFromPoint Método

Definição

Retorna o índice baseado em zero do item nas coordenadas especificadas.Returns the zero-based index of the item at the specified coordinates.

Sobrecargas

IndexFromPoint(Point)

Retorna o índice baseado em zero do item nas coordenadas especificadas.Returns the zero-based index of the item at the specified coordinates.

IndexFromPoint(Int32, Int32)

Retorna o índice baseado em zero do item nas coordenadas especificadas.Returns the zero-based index of the item at the specified coordinates.

IndexFromPoint(Point)

Retorna o índice baseado em zero do item nas coordenadas especificadas.Returns the zero-based index of the item at the specified coordinates.

public:
 int IndexFromPoint(System::Drawing::Point p);
public int IndexFromPoint (System.Drawing.Point p);
member this.IndexFromPoint : System.Drawing.Point -> int
Public Function IndexFromPoint (p As Point) As Integer

Parâmetros

p
Point

Um objeto Point que contém as coordenadas usadas para obter o índice do item.A Point object containing the coordinates used to obtain the item index.

Retornos

O índice baseado em zero do item encontrado nas coordenadas especificadas. Retornará ListBox.NoMatches se nenhuma correspondência for encontrada.The zero-based index of the item found at the specified coordinates; returns ListBox.NoMatches if no match is found.

Exemplos

O exemplo de código a seguir demonstra como executar operações de arrastar e soltar usando um controle de ListBox que contém itens a serem descartados em um controle de RichTextBox.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. O construtor do formulário define a propriedade AllowDrop como true para permitir que as operações de arrastar e soltar ocorram no RichTextBox.The constructor of the form sets the AllowDrop property to true to enable drag-and-drop operations to occur in the RichTextBox. O exemplo usa o evento MouseDown do ListBox para iniciar a operação de arrastar chamando o método DoDragDrop.The example uses the MouseDown event of the ListBox to start the drag operation by calling the DoDragDrop method. O exemplo usa o evento DragEnter para determinar se um item que está sendo arrastado para o RichTextBox é um tipo de dados válido.The example uses the DragEnter event to determine if an item being dragged into the RichTextBox is a valid data type. O evento DragDrop executa a descartação real de um item arrastado para o controle de RichTextBox no local do cursor atual dentro do RichTextBox.The DragDrop event performs the actual dropping of a dragged item into the RichTextBox control at the current cursor location within the RichTextBox. Este exemplo requer que os eventos DragDrop e DragEnter tenham sido conectados aos manipuladores de eventos definidos no exemplo.This example requires that the DragDrop and DragEnter events have been connected to the event handlers defined in the example.

public:
   Form1()
   {
      InitializeComponent();
      
      // Sets the control to allow drops, and then adds the necessary event handlers.
      this->richTextBox1->AllowDrop = true;
   }

private:
   void listBox1_MouseDown( Object^ sender, System::Windows::Forms::MouseEventArgs^ e )
   {
      // Determines which item was selected.
      ListBox^ lb = (dynamic_cast<ListBox^>(sender));
      Point pt = Point(e->X,e->Y);

      //Retrieve the item at the specified location within the ListBox.
      int index = lb->IndexFromPoint( pt );

      // Starts a drag-and-drop operation.
      if ( index >= 0 )
      {
         // Retrieve the selected item text to drag into the RichTextBox.
         lb->DoDragDrop( lb->Items[ index ]->ToString(), DragDropEffects::Copy );
      }
   }

   void richTextBox1_DragEnter( Object^ /*sender*/, DragEventArgs^ e )
   {
      // If the data is text, copy the data to the RichTextBox control.
      if ( e->Data->GetDataPresent( "Text" ) )
            e->Effect = DragDropEffects::Copy;
   }

   void richTextBox1_DragDrop( Object^ /*sender*/, DragEventArgs^ e )
   {
      // Paste the text into the RichTextBox where at selection location.
      richTextBox1->SelectedText = e->Data->GetData( "System.String", true )->ToString();
   }
public Form1()
{
   InitializeComponent();
   // Sets the control to allow drops, and then adds the necessary event handlers.
   this.richTextBox1.AllowDrop = true;
}
 
private void listBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
   // Determines which item was selected.
   ListBox lb =( (ListBox)sender);
   Point pt = new Point(e.X,e.Y);
   //Retrieve the item at the specified location within the ListBox.
   int index = lb.IndexFromPoint(pt);

   // Starts a drag-and-drop operation.
   if(index>=0) 
   {
      // Retrieve the selected item text to drag into the RichTextBox.
      lb.DoDragDrop(lb.Items[index].ToString(), DragDropEffects.Copy);
   }
}

private void richTextBox1_DragEnter(object sender, DragEventArgs e)
{
   // If the data is text, copy the data to the RichTextBox control.
   if(e.Data.GetDataPresent("Text"))
      e.Effect = DragDropEffects.Copy;
}

private void richTextBox1_DragDrop(object sender, DragEventArgs e) 
{
   // Paste the text into the RichTextBox where at selection location.
   richTextBox1.SelectedText =  e.Data.GetData("System.String", true).ToString();
}

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


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

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

Comentários

Esse método permite que você determine qual item está localizado em um local específico dentro do controle.This method enables you to determine which item is located at a specific location within the control. Você pode usar esse método para determinar qual item da lista está selecionado quando um usuário clica com o botão direito do mouse no ListBox.You can use this method to determine which item within the list is selected when a user right-clicks the ListBox. O local do cursor pode ser determinado e passado para o parâmetro p do método IndexFromPoint para determinar em qual item o usuário clicou com o botão direito do mouse.The location of the cursor can be determined and passed to the p parameter of the IndexFromPoint method to determine which item the user right-clicked the mouse over. Você pode exibir um menu de atalho para o usuário a fim de fornecer tarefas e recursos com base no item específico.You can then display a shortcut menu to the user to provide tasks and features based on the specific item.

IndexFromPoint(Int32, Int32)

Retorna o índice baseado em zero do item nas coordenadas especificadas.Returns the zero-based index of the item at the specified coordinates.

public:
 int IndexFromPoint(int x, int y);
public int IndexFromPoint (int x, int y);
member this.IndexFromPoint : int * int -> int
Public Function IndexFromPoint (x As Integer, y As Integer) As Integer

Parâmetros

x
Int32

A coordenada X do local a ser pesquisado.The x-coordinate of the location to search.

y
Int32

A coordenada Y do local a ser pesquisado.The y-coordinate of the location to search.

Retornos

O índice baseado em zero do item encontrado nas coordenadas especificadas. Retornará ListBox.NoMatches se nenhuma correspondência for encontrada.The zero-based index of the item found at the specified coordinates; returns ListBox.NoMatches if no match is found.

Exemplos

O exemplo de código a seguir demonstra como executar operações de arrastar e soltar usando um controle de ListBox que contém itens a serem descartados em um controle de RichTextBox.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. O construtor do formulário define a propriedade AllowDrop como true para permitir que as operações de arrastar e soltar ocorram no RichTextBox.The constructor of the form sets the AllowDrop property to true to enable drag-and-drop operations to occur in the RichTextBox. O exemplo usa o evento MouseDown do ListBox para iniciar a operação de arrastar chamando o método DoDragDrop.The example uses the MouseDown event of the ListBox to start the drag operation by calling the DoDragDrop method. O exemplo usa o evento DragEnter para determinar se um item que está sendo arrastado para o RichTextBox é um tipo de dados válido.The example uses the DragEnter event to determine if an item being dragged into the RichTextBox is a valid data type. O evento DragDrop executa a descartação real de um item arrastado para o controle de RichTextBox no local do cursor atual dentro do RichTextBox.The DragDrop event performs the actual dropping of a dragged item into the RichTextBox control at the current cursor location within the RichTextBox. Este exemplo requer que os eventos DragDrop e DragEnter tenham sido conectados aos manipuladores de eventos definidos no exemplo.This example requires that the DragDrop and DragEnter events have been connected to the event handlers defined in the example.

public:
   Form1()
   {
      InitializeComponent();
      
      // Sets the control to allow drops, and then adds the necessary event handlers.
      this->richTextBox1->AllowDrop = true;
   }

private:
   void listBox1_MouseDown( Object^ sender, System::Windows::Forms::MouseEventArgs^ e )
   {
      // Determines which item was selected.
      ListBox^ lb = (dynamic_cast<ListBox^>(sender));
      Point pt = Point(e->X,e->Y);

      //Retrieve the item at the specified location within the ListBox.
      int index = lb->IndexFromPoint( pt );

      // Starts a drag-and-drop operation.
      if ( index >= 0 )
      {
         // Retrieve the selected item text to drag into the RichTextBox.
         lb->DoDragDrop( lb->Items[ index ]->ToString(), DragDropEffects::Copy );
      }
   }

   void richTextBox1_DragEnter( Object^ /*sender*/, DragEventArgs^ e )
   {
      // If the data is text, copy the data to the RichTextBox control.
      if ( e->Data->GetDataPresent( "Text" ) )
            e->Effect = DragDropEffects::Copy;
   }

   void richTextBox1_DragDrop( Object^ /*sender*/, DragEventArgs^ e )
   {
      // Paste the text into the RichTextBox where at selection location.
      richTextBox1->SelectedText = e->Data->GetData( "System.String", true )->ToString();
   }
public Form1()
{
   InitializeComponent();
   // Sets the control to allow drops, and then adds the necessary event handlers.
   this.richTextBox1.AllowDrop = true;
}
 
private void listBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
   // Determines which item was selected.
   ListBox lb =( (ListBox)sender);
   Point pt = new Point(e.X,e.Y);
   //Retrieve the item at the specified location within the ListBox.
   int index = lb.IndexFromPoint(pt);

   // Starts a drag-and-drop operation.
   if(index>=0) 
   {
      // Retrieve the selected item text to drag into the RichTextBox.
      lb.DoDragDrop(lb.Items[index].ToString(), DragDropEffects.Copy);
   }
}

private void richTextBox1_DragEnter(object sender, DragEventArgs e)
{
   // If the data is text, copy the data to the RichTextBox control.
   if(e.Data.GetDataPresent("Text"))
      e.Effect = DragDropEffects.Copy;
}

private void richTextBox1_DragDrop(object sender, DragEventArgs e) 
{
   // Paste the text into the RichTextBox where at selection location.
   richTextBox1.SelectedText =  e.Data.GetData("System.String", true).ToString();
}

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


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

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

Comentários

Esse método permite que você determine qual item está localizado em um local específico dentro do controle.This method enables you to determine which item that is located at a specific location within the control. Você pode usar esse método para determinar qual item da lista está selecionado quando um usuário clica com o botão direito do mouse no ListBox.You can use this method to determine which item within the list is selected when a user right-clicks the ListBox. O local do cursor pode ser determinado e passado para os parâmetros x e y do método IndexFromPoint para determinar em qual item o usuário clicou com o botão direito do mouse.The location of the cursor can be determined and passed to the x and y parameters of the IndexFromPoint method to determine which item the user right-clicked the mouse over. Você pode exibir um menu de atalho para o usuário a fim de fornecer tarefas e recursos com base no item específico.You can then display a shortcut menu to the user to provide tasks and features based on the specific item.

Aplica-se a