Sta*_*ent 3 c# drag-and-drop winforms
我正在编写一个小项目,我想利用拖放功能来简化最终用户的一些操作.为了使应用程序更具吸引力,我想显示被拖动的对象.我已经在WPF中找到了一些资源,但是我不知道任何WPF,因此对于这个单一任务来说,完全没那么严重.我想知道如何使用"常规"C#Windows窗体完成此操作.到目前为止,我发现的所有拖放教程都只是谈论掉落效果,它只是几个图标的预设.
在这个项目之后,WPF听起来像是我想要学习的东西.
@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)