【问题标题】:How to Drag, Drop and Resize Label on a Panel at runtime? C#, winForms如何在运行时在面板上拖放和调整标签大小? C#,winForms
【发布时间】:2013-05-28 05:55:21
【问题描述】:

我有这个用于拖动面板的代码,但它没有做这件事。 我必须选择是拖放还是调整大小。 我认为我的代码在表单加载中有问题。 无论如何,我这里有 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;
    }  

【问题讨论】:

  • D+D always 需要实现 DragEnter 事件。只有在对控件的某些部分选择拖放时才使用 DragOver。使用面板的事件而不是面板上的控件会使用户难以选择放置目标。
  • 那么我需要在我的代码中进行哪些更改?
  • 反正我自己解决了。对于那些想知道它的人来说很容易。 :D
  • 您应该回答自己的问题,如果您解决了问题,请将其标记为正确答案。
  • 我觉得问比较好,这样我才能知道这个人真的很感兴趣。

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


【解决方案1】:

我使用了要移动的控件的 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;
        }
    }

【讨论】:

    猜你喜欢
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多