我可以为C#Windows应用程序拖放功能选择自定义映像吗?

Sta*_*ent 3 c# drag-and-drop winforms

我正在编写一个小项目,我想利用拖放功能来简化最终用户的一些操作.为了使应用程序更具吸引力,我想显示被拖动的对象.我已经在WPF中找到了一些资源,但是我不知道任何WPF,因此对于这个单一任务来说,完全没那么严重.我想知道如何使用"常规"C#Windows窗体完成此操作.到目前为止,我发现的所有拖放教程都只是谈论掉落效果,它只是几个图标的预设.

在这个项目之后,WPF听起来像是我想要学习的东西.

vpi*_*pkt 7

@Jesper提供的博客链接提供了两三个关键信息,但我认为值得将它带入后代的SO中.

设置自定义光标

下面的代码允许您为光标使用任意图像

 public struct IconInfo
  {
    public bool fIcon;
    public int xHotspot;
    public int yHotspot;
    public IntPtr hbmMask;
    public IntPtr hbmColor;
  }

    [DllImport("user32.dll")]
    public static extern IntPtr CreateIconIndirect(ref IconInfo icon);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);

    public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot)
    {
      IconInfo tmp = new IconInfo();
      GetIconInfo(bmp.GetHicon(), ref tmp);
      tmp.xHotspot = xHotSpot;
      tmp.yHotspot = yHotSpot;
      tmp.fIcon = false;
      return new Cursor(CreateIconIndirect(ref tmp));
    }
Run Code Online (Sandbox Code Playgroud)

设置拖放事件处理

其他教程和答案中都详细介绍了这一点.我们在这里关注的具体事件是GiveFeedback和DragEnter,在您希望应用自定义光标的任何控件上.

 private void DragSource_GiveFeedback(object sender, GiveFeedbackEventArgs e)
    {
      e.UseDefaultCursors = 0;
    }

   private void DragDest_DragEnter(object sender, DragEventArgs e)
    {

      Cursor.Current = CreateCursor(bitmap, 0, 0);
     }
Run Code Online (Sandbox Code Playgroud)

  • 该代码有一个令人讨厌的句柄泄漏,一段时间后会使您的程序崩溃。请注意,在MSDN示例代码中,对于Bitmap.GetHicon()方法,使用了DestroyIcon()。必需,但必须在游标不再使用之后完成。使用[Reflection hack](http://stackoverflow.com/a/1551567/17034),可以使Cursor类自动为您执行此操作。 (2认同)