如何在运行时拖动,删除和调整面板上的标签? C#,winForms

时间:2013-05-28 05:55:21

标签: c# winforms drag-and-drop label panel

我有这个代码用于拖动Panel,但它没有做到这一点。 我必须选择是否只是拖放或调整大小。 我觉得我的代码在表单加载方面有问题。 无论如何,我在这里有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;
    }  

1 个答案:

答案 0 :(得分: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;
        }
    }