9

我在一个表单中有 5 个面板,在两个不同的面板中有两个按钮,现在的要求是将按钮从一个面板移动到另一个面板。

请给我一个代码。

4

2 回答 2

26

为了演示,在一个表单上放置两个面板,在其中一个面板中放置一个按钮:

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;
}
于 2012-07-10T13:09:36.870 回答
0

此方法也适用于组框,但必须手动添加 MouseEnter、MouseLeave 和 MouseUp 事件:

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
    // ...
}
于 2018-03-06T23:39:13.543 回答