Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

winforms - Can I choose a custom image for C# Windows Application Drag Drop functions?

I am writing a small project where I would like to make use of drag and drop functionalty to ease some of the operations for the end user. To make the application a little more appealing, I would like to display the object being dragged. I have found some resources with WPF, but I don't know any WPF, so it becomes a bit tough to bite down on that whole subject for this single task. I would like to know how this can be done with "regular" C# Windows Forms. So far, all drag drop tutorials I've found just talk about the drop effects which is just a preset of a few icons.

WPF sounds like something I want to learn after this project.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The blog link provided by @Jesper gives the two or three key nuggets of info, but I think it is worth bringing it into S.O. for posterity.

Set up the custom cursor

The code below allows you to use an arbitrary image for your cursor

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

Set up the drag and drop event handling

This is well covered in other tutorials and answers. The specific events we are concerned about here are GiveFeedback and DragEnter, on any control where you want the custom cursor to apply.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...