-1

我的代码有问题。我正在尝试在我的表单上拖放图片,但是当我移动选定的图片框时,当我离开组框时它会丢失。它只是消失了。

public partial class Form1 : Form
{
    int x_offset = 0; // any better to do this without having a global variable?
    int y_offset = 0;

    PictureBox dpb = new PictureBox();
    public Form1()
    {
        InitializeComponent();

        this.WindowState = FormWindowState.Maximized;
        this.AllowDrop = true;
        this.pictureBox1.MouseDown += pictureBox1_MouseDown;
        this.pictureBox2.MouseDown += pictureBox2_MouseDown;
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        PictureBox me = (PictureBox)sender;
        x_offset = e.X;
        y_offset = e.Y;

    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            PictureBox me = (PictureBox)sender;
            me.Left = e.X + me.Left - x_offset;
            me.Top = e.Y + me.Top - y_offset;
        }
    }
4

2 回答 2

1

您的 PictureBoxes 正在被父级(即 GroupBox)剪辑。您可以修复层次结构(查看->其他窗口->文档大纲)。

此外,通常最好使用标准拖放功能,如下所述:http: //social.msdn.microsoft.com/Forums/en-US/92cad3ba-dd05-4aa9-ad44-411051407d57/drag-and-将图片框放到 c 中的图片框?forum=csharplanguage。这将处理所有拖放特殊情况。为了更改标准光标,请将 Cursor.Current 设置为光标,由 CreateCursor(myBitmap) 返回。注意: CreateCursor 在某些情况下可能会失败,因此请确保提供标准游标的回退。

于 2013-10-17T01:02:43.603 回答
0

PictureBox有一个GroupBox作为它的父,在winforms和许多其他 UI 技术中,你不能在它的父控件之外呈现一个子控件。在使用您的代码之前,您可能需要执行以下操作:

pictureBox1.Parent = this;//set your Form as Parent of the pictureBox1
pictureBox1.BringToFront();//Ensure your pictureBox1 is on top.

pictureBox1如果您的要求是将您从拖放GroupBox到另一个控件以使其成为您的新控件ParentpictureBox1您可以尝试以下代码:

    Point downPoint;
    //MouseDown event handler for your pictureBox1
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e){
        downPoint = e.Location;
        pictureBox1.Parent = this;
        pictureBox1.BringToFront();
    }
    //MouseMove event handler for your pictureBox1
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e){
        if (e.Button == MouseButtons.Left) {
            pictureBox1.Left += e.X - downPoint.X;
            pictureBox1.Top += e.Y - downPoint.Y;
        }
    }
    //MouseUp event handler for your pictureBox1
    private void pictureBox1_MouseUp(object sender, MouseEventArgs e) {
        Control c = GetChildAtPoint(new Point(pictureBox1.Left - 1, pictureBox1.Top));
        if (c == null) c = this;
        Point newLoc = c.PointToClient(pictureBox1.Parent.PointToScreen(pictureBox1.Location));
        pictureBox1.Parent = c;
        pictureBox1.Location = newLoc;
    }
于 2013-10-17T06:08:01.630 回答