开发者

Drag & Drop a pictureBox onto Form

开发者 https://www.devze.com 2023-04-08 21:20 出处:网络
I am writing a game. Player can choose items (such as weapon) and drag them to the form. Items are on the side, in PictureBox controls. I have set Form.AllowDr开发者_如何学JAVAop to True. When I drag

I am writing a game. Player can choose items (such as weapon) and drag them to the form. Items are on the side, in PictureBox controls. I have set Form.AllowDr开发者_如何学JAVAop to True. When I drag one of the items pictureBoxes, the pictureBox doesn't drop, neither even drag.

I want to drag a pictureBox on the form, or at least know the position in the form which the player want to drag it in.

EDIT: look at the logo above. When you click it and drag (without release) it drags.


In Winforms you need to change the cursor. Here's a complete example, start a new forms project and drop a picturebox on the form. Set its Image property to a small bitmap. Click and drag to drop copies of the image on the form.

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 = pb.Image.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);
}


For the draggable items, you need to call the DoDragDrop method in the MouseDown event. Make sure your form (or target) has the AllowDrop property set to true.

For your target, you need to wire the dragging events:

private void Form1_DragOver(object sender, DragEventArgs e)
{
  e.Effect = DragDropEffects.Copy;
}

private void Form1_DragDrop(object sender, DragEventArgs e)
{
  // Examine e.Data.GetData stuff
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号