1

我有这个用于拖动面板的代码,但它没有做这件事。我必须选择是拖放还是调整大小。我认为我的代码在表单加载中有问题。无论如何,我在这里有 5 个标签,在 panel1 上有一个名为 label1、label2、label3、label4、label5 的面板。

    private void form_Load(object sender, EventArgs e)
    {
            //for drag and drop           
            //this.panel1.AllowDrop = true; // or Allow drop in the panel.
            foreach (Control c in this.panel1.Controls)
            {
                c.MouseDown += new MouseEventHandler(c_MouseDown);
            }
            this.panel1.DragOver += new DragEventHandler(panel1_DragOver);
            this.panel1.DragDrop += new DragEventHandler(panel1_DragDrop);  

            //end of drag and drop
    }

    void c_MouseDown(object sender, MouseEventArgs e)
    {
        Control c = sender as Control;                       
            c.DoDragDrop(c, DragDropEffects.Move);
    }

    void panel1_DragDrop(object sender, DragEventArgs e)
    {

        Control c = e.Data.GetData(e.Data.GetFormats()[0]) as Control;
        lblResizeAmtWord.Visible = false;
        if (c != null)
        {
            c.Location = this.panel1.PointToClient(new Point(e.X, e.Y));
            //this.panel1.Controls.Add(c); //disable if already on the panel
        }
    }

    void panel1_DragOver(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Move;
    }  
4

1 回答 1

3

我使用了要移动的控件的 MouseDown、Up 和 Move 事件。假设我的控件名称是 ctrlToMove。

    private Point _Offset = Point.Empty;
    private void ctrlToMove_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            _Offset = new Point(e.X, e.Y);
        }
    }

    private void ctrlToMove_MouseUp(object sender, MouseEventArgs e)
    {
        _Offset = Point.Empty;
    }

    private void ctrlToMove_MouseMove(object sender, MouseEventArgs e)
    {
        if (_Offset != Point.Empty)
        {
            Point newlocation = ctrlToMove.Location;
            newlocation.X += e.X - _Offset.X;
            newlocation.Y += e.Y - _Offset.Y;
            ctrlToMove.Location = newlocation;
        }
    }
于 2014-06-25T12:30:44.517 回答