拖动n Drop in .net Treeview

时间:2011-03-26 07:09:54

标签: c# .net winforms treeview

我在Windows应用程序中使用.net树视图控件。我已经实现了拖放功能,它工作正常。现在,我想显示正在拖动的节点的文本/自定义图像及其图像,就像我们在窗口拖动文件夹时看到的那样,即我们看到文件夹的淡入淡出图像跟随光标直到掉落。

如何在.net winform app中执行此操作。

谢谢, Omky

1 个答案:

答案 0 :(得分:5)

这是一篇链接到几篇文章的第一篇,解释了如何 http://blogs.msdn.com/b/adamroot/archive/2008/02/19/shell-style-drag-and-drop-in-net-wpf-and-winforms.aspx

以下是让拖动效果起作用的最低要求。

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using ComIDataObject = System.Runtime.InteropServices.ComTypes.IDataObject;

public static class DragDropEngine
{
      public static void ProcessDragEnter(DragEventArgs e)
      {
            Point point = Cursor.Position;
            WindowsPoint winpoint;
            winpoint.X = point.X;
            winpoint.Y = point.Y;
            IDropTargetHelper dropHelper = (IDropTargetHelper)new DragDropHelper();
            dropHelper.DragEnter(IntPtr.Zero, (ComIDataObject)e.Data, 
                  ref winpoint, (int)e.Effect);
      }
      public static void ProcessDragDrop(DragEventArgs e)
      {
            Point point = Cursor.Position;
            WindowsPoint winpoint;
            winpoint.X = point.X;
            winpoint.Y = point.Y;
            IDropTargetHelper dropHelper = (IDropTargetHelper)new DragDropHelper();
            dropHelper.Drop((ComIDataObject)e.Data, ref winpoint, (int)e.Effect);
      }
      public static void ProcessDragOver(DragEventArgs e)
      {
            Point point = Cursor.Position;
            WindowsPoint winpoint;
            winpoint.X = point.X;
            winpoint.Y = point.Y;
            IDropTargetHelper dropHelper = (IDropTargetHelper)new DragDropHelper();
            dropHelper.DragOver(ref winpoint, (int)e.Effect);
      }
      public static void ProcessDragLeave(EventArgs e)
      {
            IDropTargetHelper dropHelper = (IDropTargetHelper)new DragDropHelper();
            dropHelper.DragLeave();
      }
}
[ComImport]
[Guid("4657278A-411B-11d2-839A-00C04FD918D0")]
public class DragDropHelper
{
}
[ComVisible(true)]
[ComImport]
[Guid("4657278B-411B-11D2-839A-00C04FD918D0")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDropTargetHelper
{
      void DragEnter(
          [In] IntPtr hwndTarget,
          [In, MarshalAs(UnmanagedType.Interface)] 
            System.Runtime.InteropServices.ComTypes.IDataObject dataObject,
          [In] ref WindowsPoint pt,
          [In] int effect);
      void DragLeave();
      void DragOver(
          [In] ref WindowsPoint pt,
          [In] int effect);
      void Drop(
          [In, MarshalAs(UnmanagedType.Interface)] 
            System.Runtime.InteropServices.ComTypes.IDataObject dataObject,
          [In] ref WindowsPoint pt,
          [In] int effect);
      void Show(
          [In] bool show);
}
[StructLayout(LayoutKind.Sequential)]
public struct WindowsPoint
{
      public int X;
      public int Y;
}