ListViewInsertionMark.NearestIndex(Point) Метод

Определение

Извлекает индекс элемента, ближайшего к заданной точке.

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

Параметры

pt
Point

Объект Point, представляющий местоположение, от которого должен быть найден ближайший элемент.

Возвращаемое значение

Индекс элемента, ближайшего к заданной точке, либо значение -1, если ближайший элемент является перетаскиваемым в настоящий момент.

Примеры

В следующем примере кода показано, как использовать ListView функцию метки вставки и реализуется изменение порядка элементов перетаскивания с помощью стандартных событий перетаскивания. Положение метки вставки обновляется в обработчике Control.DragOver события . В этом обработчике положение указателя мыши сравнивается с средней точкой ближайшего элемента, а результат используется для определения того, отображается ли метка вставки слева или справа от элемента.

Полный пример см. в обзорной справочной ListViewInsertionMark статье.

// 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

Комментарии

Этот метод позволяет найти элемент, ближайший к указателю мыши, при выполнении операции перетаскивания. Используйте возвращаемое значение индекса, чтобы задать Index свойство . Если наиболее близким к указателю мыши элементом является перетаскиваемый элемент, возвращаемое значение этого метода равно -1. В этом случае установка Index этого значения для свойства скрывает метку вставки.

Этот метод находит ближайший элемент независимо от того, где находится указатель мыши, в то время как ListView.GetItemAt метод возвращает элемент только в указанном расположении или null если в этом расположении нет элемента. Метод ListView.GetItemAt возвращает null, например, если указатель мыши находится между двумя элементами. По этой причине при использовании операции перетаскивания для размещения элементов всегда следует использовать NearestIndex метод .

Применяется к

См. также раздел