簡體   English   中英

將pictureBox拖放到窗體上

[英]Drag & Drop a pictureBox onto Form

我在寫游戲。 玩家可以選擇物品(例如武器)並將其拖到窗體上。 項目位於PictureBox控件的側面。 我已經將Form.AllowDrop設置為True 當我拖動其中一個項目pictureBoxes時, pictureBox不會拖放,甚至都不會拖動。

我想在窗體上拖動一個PictureBox,或者至少知道播放器要將其拖動到窗體中的位置。

編輯:看看上面的徽標。 單擊並拖動(不釋放)時,它會拖動。

在Winforms中,您需要更改光標。 這是一個完整的示例,啟動一個新的窗體項目,然后在窗體上放置一個圖片框。 將其Image屬性設置為一個小的位圖。 單擊並拖動以將圖像的副本拖放到表單上。

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);
}

對於可拖動項,您需要在MouseDown事件中調用DoDragDrop方法。 確保您的表單(或目標)的AllowDrop屬性設置為true。

對於您的目標,您需要關聯拖動事件:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM