ListBox.IndexFromPoint Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Devolve o índice baseado em zero do item nas coordenadas especificadas.
Sobrecargas
| Name | Description |
|---|---|
| IndexFromPoint(Point) |
Devolve o índice baseado em zero do item nas coordenadas especificadas. |
| IndexFromPoint(Int32, Int32) |
Devolve o índice baseado em zero do item nas coordenadas especificadas. |
IndexFromPoint(Point)
Devolve o índice baseado em zero do item nas coordenadas especificadas.
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
Devoluções
O índice baseado em zero do item encontrado nas coordenadas especificadas; Retorna ListBox.NoMatches se não for encontrada correspondência.
Exemplos
O exemplo de código seguinte demonstra como realizar operações de arrastar e largar usando um ListBox controlo que contém itens a colocar num RichTextBox controlo. O construtor do formulário define a AllowDrop propriedade para true permitir que operações de arrastar e largar ocorram no RichTextBox. O exemplo usa o MouseDown evento de para ListBox iniciar a operação de arrasto ao chamar o DoDragDrop método. O exemplo utiliza o DragEnter evento para determinar se um item que está a ser arrastado para o RichTextBox é um tipo de dado válido. O DragDrop evento executa a largada efetiva de um item arrastado para o RichTextBox controlo na posição atual do cursor dentro do RichTextBox. Este exemplo exige que os DragDrop eventos e DragEnter tenham sido ligados aos handlers de eventos definidos no exemplo.
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
Observações
Este método permite-lhe determinar qual item está localizado num local específico dentro do controlo. Pode usar este método para determinar qual o item da lista selecionado quando um utilizador clica com o botão direito no ListBox. A localização do cursor pode ser determinada e passada ao p parâmetro do IndexFromPoint método para determinar sobre qual item o utilizador clicou com o rato com o botão direito. Pode então mostrar um menu de atalho ao utilizador para fornecer tarefas e funcionalidades com base no item específico.
Aplica-se a
IndexFromPoint(Int32, Int32)
Devolve o índice baseado em zero do item nas coordenadas especificadas.
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 procurar.
- y
- Int32
A coordenada y do local a procurar.
Devoluções
O índice baseado em zero do item encontrado nas coordenadas especificadas; Retorna ListBox.NoMatches se não for encontrada correspondência.
Exemplos
O exemplo de código seguinte demonstra como realizar operações de arrastar e largar usando um ListBox controlo que contém itens a colocar num RichTextBox controlo. O construtor do formulário define a AllowDrop propriedade para true permitir que operações de arrastar e largar ocorram no RichTextBox. O exemplo usa o MouseDown evento de para ListBox iniciar a operação de arrasto ao chamar o DoDragDrop método. O exemplo utiliza o DragEnter evento para determinar se um item que está a ser arrastado para o RichTextBox é um tipo de dado válido. O DragDrop evento executa a largada efetiva de um item arrastado para o RichTextBox controlo na posição atual do cursor dentro do RichTextBox. Este exemplo exige que os DragDrop eventos e DragEnter tenham sido ligados aos handlers de eventos definidos no exemplo.
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
Observações
Este método permite-lhe determinar qual o item que está localizado num local específico dentro do controlo. Pode usar este método para determinar qual o item da lista selecionado quando um utilizador clica com o botão direito no ListBox. A localização do cursor pode ser determinada e passada aos x parâmetros e y do IndexFromPoint método para determinar sobre qual item o utilizador clicou com o rato com o botão direito. Pode então mostrar um menu de atalho ao utilizador para fornecer tarefas e funcionalidades com base no item específico.