Move button controls in a Windows Forms application inside a panel container

Asked

Viewed 61 times

2

I have a form with three buttons, are they: btnVendas, btnFunctionaries, btnConfig. And they’re lined up inside a Panel container. I need these buttons to be clicked and held by the mouse pointer so that the user can place them in the place they prefer by just dragging them from one position to the other, being the space allowed only within the area of the container Panel that encompasses them.

  • Here has a good response demonstrating how to drag-n-drop if you want.

  • Very cool the content of the link, however, there are some differences, here I just want to move the buttons dragging with the mouse pointer, and so position them in a different location from the initial within the same space, in case, inside the panel.

1 answer

0

private void Form1_Load(object sender, EventArgs e)
{
    panel1.AllowDrop = true;
    panel1.DragEnter += Panel1_DragEnter;
    panel1.DragDrop += Panel1_DragDrop;            
    button2.MouseDown += Button2_MouseDown;
}


private void Button2_MouseDown(object sender, MouseEventArgs e)
{
    button2.DoDragDrop(button2, DragDropEffects.Move);
}

private void Panel1_DragDrop(object sender, DragEventArgs e)
{
    var btn = ((Button)e.Data.GetData(typeof(Button)));
    var point = panel1.PointToClient(new Point(e.X, e.Y));
    btn.Left = point.X;
    btn.Top = point.Y;
}

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.