다음을 통해 공유


ItemDragEventHandler 대리자

ListView 또는 TreeView 컨트롤의 ItemDrag 이벤트를 처리할 메서드를 나타냅니다.

네임스페이스: System.Windows.Forms
어셈블리: System.Windows.Forms(system.windows.forms.dll)

구문

‘선언
Public Delegate Sub ItemDragEventHandler ( _
    sender As Object, _
    e As ItemDragEventArgs _
)
‘사용 방법
Dim instance As New ItemDragEventHandler(AddressOf HandlerMethod)
public delegate void ItemDragEventHandler (
    Object sender,
    ItemDragEventArgs e
)
public delegate void ItemDragEventHandler (
    Object^ sender, 
    ItemDragEventArgs^ e
)
/** @delegate */
public delegate void ItemDragEventHandler (
    Object sender, 
    ItemDragEventArgs e
)
JScript에서는 대리자를 사용할 수 있지만 새로 선언할 수는 없습니다.

매개 변수

  • sender
    이벤트 소스입니다.

설명

ItemDragEventHandler 대리자를 만드는 경우 이벤트를 처리할 메서드를 결정합니다. 이벤트를 이벤트 처리기와 연결하려면 대리자의 인스턴스를 해당 이벤트에 추가합니다. 대리자를 제거하지 않는 경우 이벤트가 발생할 때마다 이벤트 처리기가 호출됩니다. 이벤트 처리기 대리자에 대한 자세한 내용은 이벤트 및 대리자를 참조하십시오.

예제

다음 예제에서는 TreeView 컨트롤 내에서 끌어서 놓기 작업을 활성화하는 방법을 보여 줍니다. 이 예제에서는 모든 노드를 해당 노드의 하위 노드가 아닌 다른 노드로 끌어 올 수 있습니다. 끌어 오는 노드는 해당 노드의 모든 하위 노드를 포함하여 대상 노드의 자식 노드가 됩니다. 마우스 왼쪽 단추를 사용할 경우에는 끌어 오는 노드가 대상 노드로 이동하고, 마우스 오른쪽 단추를 사용할 경우에는 끌어 오는 노드가 대상 노드로 복사됩니다.

Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
    Inherits Form
    Private treeView1 As TreeView

    Public Sub New()
        treeView1 = New TreeView()
        
        Me.SuspendLayout()
        
        ' Initialize treeView1.
        treeView1.AllowDrop = True
        treeView1.Dock = DockStyle.Fill
        
        ' Add nodes to treeView1.
        Dim node As TreeNode
        Dim x As Integer
        For x = 0 To 3
            ' Add a root node to treeView1.
            node = treeView1.Nodes.Add(String.Format("Node{0}", x * 4))
            Dim y As Integer
            For y = 1 To 4
                ' Add a child node to the previously added node.
                node = node.Nodes.Add(String.Format("Node{0}", x * 4 + y))
            Next y
        Next x

        ' Add event handlers for the required drag events.
        AddHandler treeView1.ItemDrag, AddressOf treeView1_ItemDrag
        AddHandler treeView1.DragEnter, AddressOf treeView1_DragEnter
        AddHandler treeView1.DragOver, AddressOf treeView1_DragOver
        AddHandler treeView1.DragDrop, AddressOf treeView1_DragDrop

        ' Initialize the form.
        Me.ClientSize = New Size(292, 273)
        Me.Controls.Add(treeView1)

        Me.ResumeLayout(False)
    End Sub 'New

    Shared Sub Main()
        Application.Run(New Form1)
    End Sub 'Main

    Private Sub treeView1_ItemDrag(ByVal sender As Object, ByVal e As ItemDragEventArgs)

        ' Move the dragged node when the left mouse button is used.
        If e.Button = MouseButtons.Left Then
            DoDragDrop(e.Item, DragDropEffects.Move)

        ' Copy the dragged node when the right mouse button is used.
        ElseIf e.Button = MouseButtons.Right Then
            DoDragDrop(e.Item, DragDropEffects.Copy)
        End If
    End Sub 'treeView1_ItemDrag

    ' Set the target drop effect to the effect 
    ' specified in the ItemDrag event handler.
    Private Sub treeView1_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs)
        e.Effect = e.AllowedEffect
    End Sub 'treeView1_DragEnter

    ' Select the node under the mouse pointer to indicate the 
    ' expected drop location.
    Private Sub treeView1_DragOver(ByVal sender As Object, ByVal e As DragEventArgs)
        ' Retrieve the client coordinates of the mouse position.
        Dim targetPoint As Point = treeView1.PointToClient(new Point(e.X, e.Y))

        ' Select the node at the mouse position.
        treeView1.SelectedNode = treeView1.GetNodeAt(targetPoint)
    End Sub 'treeView1_DragOver

    Private Sub treeView1_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs)

        ' Retrieve the client coordinates of the drop location.
        Dim targetPoint As Point = treeView1.PointToClient(New Point(e.X, e.Y))

        ' Retrieve the node at the drop location.
        Dim targetNode As TreeNode = treeView1.GetNodeAt(targetPoint)

        ' Retrieve the node that was dragged.
        Dim draggedNode As TreeNode = CType(e.Data.GetData(GetType(TreeNode)), TreeNode)

        ' Confirm that the node at the drop location is not 
        ' the dragged node or a descendant of the dragged node.
        If Not draggedNode.Equals(targetNode) AndAlso Not ContainsNode(draggedNode, targetNode) Then

            ' If it is a move operation, remove the node from its current 
            ' location and add it to the node at the drop location.
            If e.Effect = DragDropEffects.Move Then
                draggedNode.Remove()
                targetNode.Nodes.Add(draggedNode)

            ' If it is a copy operation, clone the dragged node 
            ' and add it to the node at the drop location.
            ElseIf e.Effect = DragDropEffects.Copy Then
                targetNode.Nodes.Add(CType(draggedNode.Clone(), TreeNode))
            End If

            ' Expand the node at the location 
            ' to show the dropped node.
            targetNode.Expand()
        End If
    End Sub 'treeView1_DragDrop

    ' Determine whether one node is a parent 
    ' or ancestor of a second node.
    Private Function ContainsNode(ByVal node1 As TreeNode, ByVal node2 As TreeNode) As Boolean

        ' Check the parent node of the second node.
        If node2.Parent Is Nothing Then
            Return False
        End If
        If node2.Parent.Equals(node1) Then
            Return True
        End If

        ' If the parent node is not null or equal to the first node, 
        ' call the ContainsNode method recursively using the parent of 
        ' the second node.
        Return ContainsNode(node1, node2.Parent)
    End Function 'ContainsNode

End Class 'Form1 
using System;
using System.Drawing;
using System.Windows.Forms;

public class Form1 : Form
{
    private TreeView treeView1;

    public Form1()
    {
        treeView1 = new TreeView();

        this.SuspendLayout();

        // Initialize treeView1.
        treeView1.AllowDrop = true;
        treeView1.Dock = DockStyle.Fill;

        // Add nodes to treeView1.
        TreeNode node;
        for (int x = 0; x < 3; ++x)
        {
            // Add a root node to treeView1.
            node = treeView1.Nodes.Add(String.Format("Node{0}", x*4));
            for (int y = 1; y < 4; ++y)
            {
                // Add a child node to the previously added node.
                node = node.Nodes.Add(String.Format("Node{0}", x*4 + y));
            }
        }

        // Add event handlers for the required drag events.
        treeView1.ItemDrag += new ItemDragEventHandler(treeView1_ItemDrag);
        treeView1.DragEnter += new DragEventHandler(treeView1_DragEnter);
        treeView1.DragOver += new DragEventHandler(treeView1_DragOver);
        treeView1.DragDrop += new DragEventHandler(treeView1_DragDrop);

        // Initialize the form.
        this.ClientSize = new Size(292, 273);
        this.Controls.Add(treeView1);

        this.ResumeLayout(false);
    }

    [STAThread]
    static void Main() 
    {
        Application.Run(new Form1());
    }

    private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
    {
        // Move the dragged node when the left mouse button is used.
        if (e.Button == MouseButtons.Left)
        {
            DoDragDrop(e.Item, DragDropEffects.Move);
        }

        // Copy the dragged node when the right mouse button is used.
        else if (e.Button == MouseButtons.Right)
        {
            DoDragDrop(e.Item, DragDropEffects.Copy);
        }
    }

    // Set the target drop effect to the effect 
    // specified in the ItemDrag event handler.
    private void treeView1_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = e.AllowedEffect;
    }

    // Select the node under the mouse pointer to indicate the 
    // expected drop location.
    private void treeView1_DragOver(object sender, DragEventArgs e)
    {
        // Retrieve the client coordinates of the mouse position.
        Point targetPoint = treeView1.PointToClient(new Point(e.X, e.Y));

        // Select the node at the mouse position.
        treeView1.SelectedNode = treeView1.GetNodeAt(targetPoint);
    }

    private void treeView1_DragDrop(object sender, DragEventArgs e)
    {
        // Retrieve the client coordinates of the drop location.
        Point targetPoint = treeView1.PointToClient(new Point(e.X, e.Y));

        // Retrieve the node at the drop location.
        TreeNode targetNode = treeView1.GetNodeAt(targetPoint);

        // Retrieve the node that was dragged.
        TreeNode draggedNode = (TreeNode)e.Data.GetData(typeof(TreeNode));

        // Confirm that the node at the drop location is not 
        // the dragged node or a descendant of the dragged node.
        if (!draggedNode.Equals(targetNode) && !ContainsNode(draggedNode, targetNode))
        {
            // If it is a move operation, remove the node from its current 
            // location and add it to the node at the drop location.
            if (e.Effect == DragDropEffects.Move)
            {
                draggedNode.Remove();
                targetNode.Nodes.Add(draggedNode);
            }

            // If it is a copy operation, clone the dragged node 
            // and add it to the node at the drop location.
            else if (e.Effect == DragDropEffects.Copy)
            {
                targetNode.Nodes.Add((TreeNode)draggedNode.Clone());
            }

            // Expand the node at the location 
            // to show the dropped node.
            targetNode.Expand();
        }
    }

    // Determine whether one node is a parent 
    // or ancestor of a second node.
    private bool ContainsNode(TreeNode node1, TreeNode node2)
    {
        // Check the parent node of the second node.
        if (node2.Parent == null) return false;
        if (node2.Parent.Equals(node1)) return true;

        // If the parent node is not null or equal to the first node, 
        // call the ContainsNode method recursively using the parent of 
        // the second node.
        return ContainsNode(node1, node2.Parent);
    }

}
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
public ref class Form1: public Form
{
private:
   TreeView^ treeView1;

public:
   Form1()
   {
      treeView1 = gcnew TreeView;
      this->SuspendLayout();
      
      // Initialize treeView1.
      treeView1->AllowDrop = true;
      treeView1->Dock = DockStyle::Fill;
      
      // Add nodes to treeView1.
      TreeNode^ node;
      for ( int x = 0; x < 3; ++x )
      {
         
         // Add a root node to treeView1.
         node = treeView1->Nodes->Add( String::Format( "Node{0}", x * 4 ) );
         for ( int y = 1; y < 4; ++y )
         {
            
            // Add a child node to the previously added node.
            node = node->Nodes->Add( String::Format( "Node{0}", x * 4 + y ) );

         }
      }
      
      // Add event handlers for the required drag events.
      treeView1->ItemDrag += gcnew ItemDragEventHandler( this, &Form1::treeView1_ItemDrag );
      treeView1->DragEnter += gcnew DragEventHandler( this, &Form1::treeView1_DragEnter );
      treeView1->DragOver += gcnew DragEventHandler( this, &Form1::treeView1_DragOver );
      treeView1->DragDrop += gcnew DragEventHandler( this, &Form1::treeView1_DragDrop );
      
      // Initialize the form.
      this->ClientSize = System::Drawing::Size( 292, 273 );
      this->Controls->Add( treeView1 );
      this->ResumeLayout( false );
   }

private:
   void treeView1_ItemDrag( Object^ /*sender*/, ItemDragEventArgs^ e )
   {
      
      // Move the dragged node when the left mouse button is used.
      if ( e->Button == ::MouseButtons::Left )
      {
         DoDragDrop( e->Item, DragDropEffects::Move );
      }
      // Copy the dragged node when the right mouse button is used.
      else
      
      // Copy the dragged node when the right mouse button is used.
      if ( e->Button == ::MouseButtons::Right )
      {
         DoDragDrop( e->Item, DragDropEffects::Copy );
      }
   }

   // Set the target drop effect to the effect 
   // specified in the ItemDrag event handler.
   void treeView1_DragEnter( Object^ /*sender*/, DragEventArgs^ e )
   {
      e->Effect = e->AllowedEffect;
   }

   // Select the node under the mouse pointer to indicate the 
   // expected drop location.
   void treeView1_DragOver( Object^ /*sender*/, DragEventArgs^ e )
   {
      // Retrieve the client coordinates of the mouse position.
      Point targetPoint = treeView1->PointToClient( Point(e->X,e->Y) );
      
      // Select the node at the mouse position.
      treeView1->SelectedNode = treeView1->GetNodeAt( targetPoint );
   }

   void treeView1_DragDrop( Object^ /*sender*/, DragEventArgs^ e )
   {
      // Retrieve the client coordinates of the drop location.
      Point targetPoint = treeView1->PointToClient( Point(e->X,e->Y) );
      
      // Retrieve the node at the drop location.
      TreeNode^ targetNode = treeView1->GetNodeAt( targetPoint );
      
      // Retrieve the node that was dragged.
      TreeNode^ draggedNode = dynamic_cast<TreeNode^>(e->Data->GetData( TreeNode::typeid ));
      
      // Confirm that the node at the drop location is not 
      // the dragged node or a descendant of the dragged node.
      if (  !draggedNode->Equals( targetNode ) &&  !ContainsNode( draggedNode, targetNode ) )
      {
         
         // If it is a move operation, remove the node from its current 
         // location and add it to the node at the drop location.
         if ( e->Effect == DragDropEffects::Move )
         {
            draggedNode->Remove();
            targetNode->Nodes->Add( draggedNode );
         }
         // If it is a copy operation, clone the dragged node 
         // and add it to the node at the drop location.
         else
         
         // If it is a copy operation, clone the dragged node 
         // and add it to the node at the drop location.
         if ( e->Effect == DragDropEffects::Copy )
         {
            targetNode->Nodes->Add( dynamic_cast<TreeNode^>(draggedNode->Clone()) );
         }
         
         // Expand the node at the location 
         // to show the dropped node.
         targetNode->Expand();
      }
   }

   // Determine whether one node is a parent 
   // or ancestor of a second node.
   bool ContainsNode( TreeNode^ node1, TreeNode^ node2 )
   {
      // Check the parent node of the second node.
      if ( node2->Parent == nullptr )
            return false;

      if ( node2->Parent->Equals( node1 ) )
            return true;
      
      // If the parent node is not null or equal to the first node, 
      // call the ContainsNode method recursively using the parent of 
      // the second node.
      return ContainsNode( node1, node2->Parent );
   }
};

[STAThread]
int main()
{
   Application::Run( gcnew Form1 );
}
import System.*;
import System.Drawing.*;
import System.Windows.Forms.*;

public class Form1 extends Form
{
    private TreeView treeView1;

    public Form1()
    {
        treeView1 = new TreeView();

        this.SuspendLayout();
        // Initialize treeView1.
        treeView1.set_AllowDrop(true);
        treeView1.set_Dock(DockStyle.Fill);
        // Add nodes to treeView1.
        TreeNode node;
        for (int x = 0; x < 3; ++x) {
            // Add a root node to treeView1.
            node = treeView1.get_Nodes().Add(String.
                Format("Node{0}", (Int32)(x * 4)));
            for (int y = 1; y < 4; ++y) {
                // Add a child node to the previously added node.
                node = node.get_Nodes().Add(String.
                    Format("Node{0}", (Int32)(x * 4 + y)));
            }
        }
        // Add event handlers for the required drag events.
        treeView1.add_ItemDrag(new ItemDragEventHandler(treeView1_ItemDrag));
        treeView1.add_DragEnter(new DragEventHandler(treeView1_DragEnter));
        treeView1.add_DragOver(new DragEventHandler(treeView1_DragOver));
        treeView1.add_DragDrop(new DragEventHandler(treeView1_DragDrop));
        // Initialize the form.
        this.set_ClientSize(new Size(292, 273));
        this.get_Controls().Add(treeView1);

        this.ResumeLayout(false);
    } //Form1

    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        Application.Run(new Form1());
    } //main

    private void treeView1_ItemDrag(Object sender, ItemDragEventArgs e)
    {
        // Move the dragged node when the left mouse button is used.
        if (e.get_Button().Equals(get_MouseButtons().Left)) {
            DoDragDrop(e.get_Item(), DragDropEffects.Move);
        }
        // Copy the dragged node when the right mouse button is used.
        else {
            if (e.get_Button().Equals(get_MouseButtons().Right)) {
                DoDragDrop(e.get_Item(), DragDropEffects.Copy);
            }
        }
    } //treeView1_ItemDrag

    // Set the target drop effect to the effect 
    // specified in the ItemDrag event handler.
    private void treeView1_DragEnter(Object sender, DragEventArgs e)
    {
        e.set_Effect(e.get_AllowedEffect());
    } //treeView1_DragEnter

    // Select the node under the mouse pointer to indicate the 
    // expected drop location.
    private void treeView1_DragOver(Object sender, DragEventArgs e)
    {
        // Retrieve the client coordinates of the mouse position.
        Point targetPoint =
            treeView1.PointToClient(new Point(e.get_X(), e.get_Y()));
        // Select the node at the mouse position.
        treeView1.set_SelectedNode(treeView1.GetNodeAt(targetPoint));
    } //treeView1_DragOver

    private void treeView1_DragDrop(Object sender, DragEventArgs e)
    {
        // Retrieve the client coordinates of the drop location.
        Point targetPoint =
            treeView1.PointToClient(new Point(e.get_X(), e.get_Y()));
        // Retrieve the node at the drop location.
        TreeNode targetNode = treeView1.GetNodeAt(targetPoint);
        // Retrieve the node that was dragged.
        TreeNode draggedNode =
            (TreeNode)e.get_Data().GetData(TreeNode.class.ToType());
        // Confirm that the node at the drop location is not 
        // the dragged node or a descendant of the dragged node.
        if (!(draggedNode.Equals(targetNode))
            && !(ContainsNode(draggedNode, targetNode))) {
            // If it is a move operation, remove the node from its current 
            // location and add it to the node at the drop location.
            if (e.get_Effect().Equals(DragDropEffects.Move)) {
                draggedNode.Remove();
                targetNode.get_Nodes().Add(draggedNode);
            }
            // If it is a copy operation, clone the dragged node 
            // and add it to the node at the drop location.
            else {
                if (e.get_Effect().Equals(DragDropEffects.Copy)) {
                    targetNode.get_Nodes().Add((TreeNode)draggedNode.Clone());
                }
            }
            // Expand the node at the location 
            // to show the dropped node.
            targetNode.Expand();
        }
    } //treeView1_DragDrop

    // Determine whether one node is a parent 
    // or ancestor of a second node.
    private boolean ContainsNode(TreeNode node1, TreeNode node2)
    {
        // Check the parent node of the second node.
        if (node2.get_Parent() == null) {
            return false;
        }
        if (node2.get_Parent().Equals(node1)) {
            return true;
        }
        // If the parent node is not null or equal to the first node, 
        // call the ContainsNode method recursively using the parent of 
        // the second node.
        return ContainsNode(node1, node2.get_Parent());
    } //ContainsNode
} //Form1 

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

참고 항목

참조

System.Windows.Forms 네임스페이스
ItemDragEventArgs 클래스