使用拖放移动

时间:2013-01-11 14:13:39

标签: c# visual-studio picturebox

我正在尝试使用Drag and Drop移动PictureBox。使用我的代码,克隆了PictureBox。但我需要能够移动它。我怎么能这样做?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.AllowDrop = true;
        this.pictureBox1.MouseDown += pictureBox1_MouseDown;
    }
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            var dragImage = (Bitmap)pictureBox1.Image;
            IntPtr icon = dragImage.GetHicon();
            Cursor.Current = new Cursor(icon);
            DoDragDrop(pictureBox1.Image, DragDropEffects.Copy);
            DestroyIcon(icon);
        }
    }
    protected override void OnGiveFeedback(GiveFeedbackEventArgs e)
    {
        e.UseDefaultCursors = false;
    }
    protected override void OnDragEnter(DragEventArgs e)
    {
        if (e.Data.GetDataPresent(typeof(Bitmap))) e.Effect = DragDropEffects.Copy;
    }
    protected override void OnDragDrop(DragEventArgs e)
    {
        var bmp = (Bitmap)e.Data.GetData(typeof(Bitmap));
        var pb = new PictureBox();
        pb.Image = (Bitmap)e.Data.GetData(typeof(Bitmap));
        pb.Size = pictureBox1.Size;
        pb.Location = this.PointToClient(new Point(e.X - pb.Width / 2, e.Y - pb.Height / 2));
        this.Controls.Add(pb);
    }

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    extern static bool DestroyIcon(IntPtr handle);
}

2 个答案:

答案 0 :(得分:3)

不要创建新的PictureBox,只需将旧版本的位置更新到放置位置即可。也就是说,而不是:

protected override void OnDragDrop(DragEventArgs e)
{
    var bmp = (Bitmap)e.Data.GetData(typeof(Bitmap));
    var pb = new PictureBox();
    pb.Image = (Bitmap)e.Data.GetData(typeof(Bitmap));
    pb.Size = pictureBox1.Size;
    pb.Location = this.PointToClient(new Point(e.X - pb.Width / 2, e.Y - pb.Height / 2));
    this.Controls.Add(pb);
}

只需使用:

protected override void OnDragDrop(DragEventArgs e)
{
    pictureBox1.Location = this.PointToClient(new Point(e.X - pictureBox1.Width / 2, e.Y - pictureBox1.Height / 2));
}

答案 1 :(得分:1)

这是一个扩展方法,可以为任何WinForms控件执行此操作:http://www.codeproject.com/Tips/178587/Draggable-WinForms-Controls?display=Print