ListViewInsertionMark.NearestIndex(Point) Método

Definição

Recupera o índice do item mais próximo do ponto especificado.

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

Parâmetros

pt
Point

A Point representa o local de onde se encontra o item mais próximo.

Devoluções

O índice do item mais próximo do ponto especificado ou -1 se o item mais próximo for o que está a ser arrastado.

Exemplos

O exemplo de código seguinte demonstra como usar a ListView funcionalidade de marcação de inserção e implementa a reordenação de itens por arrastar e largar usando os eventos padrão de arrastar. A posição da marca de inserção é atualizada num handler para o Control.DragOver evento. Neste manipulador, a posição do ponteiro do rato é comparada ao ponto médio do item mais próximo, e o resultado é usado para determinar se a marca de inserção aparece à esquerda ou à direita do item.

Para o exemplo completo, consulte o ListViewInsertionMark tópico de referência de visão geral.

// Moves the insertion mark as the item is dragged.
void myListView_DragOver( Object^ /*sender*/, DragEventArgs^ e )
{
   // Retrieve the client coordinates of the mouse pointer.
   Point targetPoint = myListView->PointToClient( Point(e->X,e->Y) );

   // Retrieve the index of the item closest to the mouse pointer.
   int targetIndex = myListView->InsertionMark->NearestIndex( targetPoint );

   // Confirm that the mouse pointer is not over the dragged item.
   if ( targetIndex > -1 )
   {
      // Determine whether the mouse pointer is to the left or
      // the right of the midpoint of the closest item and set
      // the InsertionMark.AppearsAfterItem property accordingly.
      Rectangle itemBounds = myListView->GetItemRect( targetIndex );
      if ( targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) )
      {
         myListView->InsertionMark->AppearsAfterItem = true;
      }
      else
      {
         myListView->InsertionMark->AppearsAfterItem = false;
      }
   }

   // Set the location of the insertion mark. If the mouse is
   // over the dragged item, the targetIndex value is -1 and
   // the insertion mark disappears.
   myListView->InsertionMark->Index = targetIndex;
}
// Moves the insertion mark as the item is dragged.
private void myListView_DragOver(object sender, DragEventArgs e)
{
    // Retrieve the client coordinates of the mouse pointer.
    Point targetPoint = 
        myListView.PointToClient(new Point(e.X, e.Y));

    // Retrieve the index of the item closest to the mouse pointer.
    int targetIndex = myListView.InsertionMark.NearestIndex(targetPoint);

    // Confirm that the mouse pointer is not over the dragged item.
    if (targetIndex > -1) 
    {
        // Determine whether the mouse pointer is to the left or
        // the right of the midpoint of the closest item and set
        // the InsertionMark.AppearsAfterItem property accordingly.
        Rectangle itemBounds = myListView.GetItemRect(targetIndex);
        if ( targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) )
        {
            myListView.InsertionMark.AppearsAfterItem = true;
        }
        else
        {
            myListView.InsertionMark.AppearsAfterItem = false;
        }
    }

    // Set the location of the insertion mark. If the mouse is
    // over the dragged item, the targetIndex value is -1 and
    // the insertion mark disappears.
    myListView.InsertionMark.Index = targetIndex;
}
' Moves the insertion mark as the item is dragged.
Private Sub myListView_DragOver(sender As Object, e As DragEventArgs)
    ' Retrieve the client coordinates of the mouse pointer.
    Dim targetPoint As Point = myListView.PointToClient(New Point(e.X, e.Y))
    
    ' Retrieve the index of the item closest to the mouse pointer.
    Dim targetIndex As Integer = _
        myListView.InsertionMark.NearestIndex(targetPoint)
    
    ' Confirm that the mouse pointer is not over the dragged item.
    If targetIndex > -1 Then
        ' Determine whether the mouse pointer is to the left or
        ' the right of the midpoint of the closest item and set
        ' the InsertionMark.AppearsAfterItem property accordingly.
        Dim itemBounds As Rectangle = myListView.GetItemRect(targetIndex)
        If targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) Then
            myListView.InsertionMark.AppearsAfterItem = True
        Else
            myListView.InsertionMark.AppearsAfterItem = False
        End If
    End If
    
    ' Set the location of the insertion mark. If the mouse is
    ' over the dragged item, the targetIndex value is -1 and
    ' the insertion mark disappears.
    myListView.InsertionMark.Index = targetIndex
End Sub

Observações

Este método permite-lhe localizar o item mais próximo do ponteiro do rato ao fazer uma operação de arrastar e largar. Use o valor do índice devolvido para definir a Index propriedade. Quando o item mais próximo do ponteiro do rato é o item a ser arrastado, o valor de retorno deste método é -1. Neste caso, definir a Index propriedade para este valor esconde a marca de inserção.

Este método encontra o item mais próximo independentemente da localização do ponteiro do rato, enquanto o ListView.GetItemAt método devolve o item apenas na localização especificada, ou null se não houver item nesse local. O ListView.GetItemAt método devolve null, por exemplo, quando o ponteiro do rato está localizado entre dois itens. Por esta razão, deve sempre usar o NearestIndex método ao usar uma operação de arrastar e largar para posicionar os itens.

Aplica-se a

Ver também