Created
May 2, 2014 22:55
-
-
Save thomaslevesque/837d1a8295b33be2b404 to your computer and use it in GitHub Desktop.
Drag and drop with custom cursor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Assembly references:
Namespaces to import: