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

我正在编写一个小项目,我想利用拖放function来简化最终用户的一些操作。 为了使应用程序更具吸引力,我想显示被拖动的对象。 我已经找到了WPF的一些资源,但是我不知道任何WPF,所以对于这个单一任务来说,对于整个主题的讨论变得有点困难。 我想知道如何使用“常规”C#Windows窗体来完成此操作。 到目前为止,我发现的所有拖放教程都只是谈论掉落效果,它只是几个图标的预设。

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

您需要隐藏默认光标并创建包含自定义图像的窗口,然后使用鼠标的位置移动该窗口。

您也可以查看http://web.archive.org/web/20130127145542/http://www.switchonthecode.com/tutorials/winforms-using-custom-cursors-with-drag-drop

更新2015-11-26

更新了链接以指向archive.org的上一个快照

@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)); } 

设置拖放事件处理

其他教程和答案中都详细介绍了这一点。 我们在这里关注的具体事件是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); }