Skip to content

Instantly share code, notes, and snippets.

@thomaslevesque
Created May 2, 2014 22:55
Show Gist options
  • Save thomaslevesque/837d1a8295b33be2b404 to your computer and use it in GitHub Desktop.
Save thomaslevesque/837d1a8295b33be2b404 to your computer and use it in GitHub Desktop.
Drag and drop with custom cursor
void Main()
{
var pb = new PictureBox { Image = Image.FromFile(@"D:\tmp\dotnet.png") };
bool down = false;
Cursor dragCursor = null;
pb.MouseDown += (sender, e) => down = true;
pb.MouseUp += (sender, e) => { down = false; dragCursor = null; };
pb.MouseMove += (sender, e) =>
{
if (down)
{
dragCursor = CreateCursor((Bitmap)pb.Image, pb.Image.Width / 2, pb.Image.Height / 2);
pb.DoDragDrop(pb.Image, DragDropEffects.Copy);
}
};
pb.GiveFeedback += (sender, e) =>
{
if (dragCursor != null)
{
Cursor.Current = dragCursor;
e.UseDefaultCursors = false;
}
};
pb.Dump();
}
public struct IconInfo
{
public bool fIcon;
public int xHotspot;
public int yHotspot;
public IntPtr hbmMask;
public IntPtr hbmColor;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);
[DllImport("user32.dll")]
public static extern IntPtr CreateIconIndirect(ref IconInfo icon);
public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot)
{
IntPtr ptr = bmp.GetHicon();
IconInfo tmp = new IconInfo();
GetIconInfo(ptr, ref tmp);
tmp.xHotspot = xHotSpot;
tmp.yHotspot = yHotSpot;
tmp.fIcon = false;
ptr = CreateIconIndirect(ref tmp);
return new Cursor(ptr);
}
@thomaslevesque
Copy link
Author

Assembly references:

  • System.Windows.Forms

Namespaces to import:

  • System.Windows.Forms
  • System.Drawing
  • System.Runtime.InteropServices

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment