How to drag and drop a button from one panel to an

2019-01-06 18:43发布

I have 5 panels in a form and two buttons in two different panels, now the requirement is to move the buttons from one panel to another.

Please suggest me a code.

标签: c# winforms
2条回答
SAY GOODBYE
2楼-- · 2019-01-06 19:06

For demonstration, place two panels on a form and a button in one of the panels:

public Form1() {
  InitializeComponent();

  panel1.AllowDrop = true;
  panel2.AllowDrop = true;

  panel1.DragEnter += panel_DragEnter;
  panel2.DragEnter += panel_DragEnter;

  panel1.DragDrop += panel_DragDrop;
  panel2.DragDrop += panel_DragDrop;

  button1.MouseDown += button1_MouseDown;
}

void button1_MouseDown(object sender, MouseEventArgs e) {
  button1.DoDragDrop(button1, DragDropEffects.Move);
}

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

void panel_DragDrop(object sender, DragEventArgs e) {
  ((Button)e.Data.GetData(typeof(Button))).Parent = (Panel)sender;
}
查看更多
Summer. ? 凉城
3楼-- · 2019-01-06 19:07

This approach also works for Group Boxes, but the MouseEnter, MouseLeave, and MouseUp events must be added manually:

public frmMain ( ) {
    InitializeComponent ( );

    pbxMoveIt.BringToFront ( );
    gbx1.AllowDrop = true;
    gbx2.AllowDrop = true;
    lblStatus.Text = "GUI Status: Started";
    gbx1.MouseEnter += gbx_MouseEnter;
    gbx1.MouseLeave += gbx_MouseLeave;
    gbx1.MouseUp += gbx_MouseUp;
    gbx2.MouseEnter += gbx_MouseEnter;
    gbx2.MouseLeave += gbx_MouseLeave;
    gbx2.MouseUp += gbx_MouseUp;
}

private void gbx_MouseEnter ( object sender, EventArgs e ) {
    // useful code
    // ...
}
private void gbx_MouseLeave ( object sender, EventArgs e ) {
    // useful code
    // ...
}
private void gbx_MouseUp ( object sender, EventArgs e ) {
    // useful code
    // ...
}
查看更多
登录 后发表回答