I am working on a Windows Forms project using C# where I use a groupbox as a container and add items to it (Labels, pictureBoxes...). I would like to know if is it possible to implement a drag and drop event on this control to move the items using the mouse or if I have to implement this event in the controls I add to my groupBox.

有帮助吗?

解决方案

after some research about my topic, i found the solution with a help from a friend of mine. To do this task, we need to use some variables, properties and three mouse events to assign to the objects: MouseMove, MouseUp and MouseDown. I also found an example recently: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/6eb864ff-0ea8-4641-bc2a-83db94371429

其他提示

This code is for copying a control(here we have done for Button. You can use any control by changing Button class to any other class in DragDrop event) to a groupbox.

First of all set the "AllowDrop" property of Groupbox to true.

groupBox5.AllowDrop=true;

Create a "DragEnter" event for Groupbox from properties window

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

Next, create a "DragDrop" event for Groupbox from properties window

private void groupBox5_DragDrop(object sender, DragEventArgs e)
{
     Control c = e.Data.GetData(e.Data.GetFormats()[0]) as Control;
     // Declare rnd globally for creating random id for dynamic button(eg : Random rnd = new Random();)
     Button btn = new Button();
     btn.Name = "Button" + rnd.Next(); 
     btn.Size = c.Size;            
     btn.Click += new System.EventHandler(DynamicButton_Click);
     if (c != null)
     {                
         btn.Text = c.Text;
         btn.Location = this.groupBox5.PointToClient(new Point(e.X, e.Y));
         this.groupBox5.Controls.Add(btn);
     }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top