C# 如何将按钮从一个面板拖放到另一个面板?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11407068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:45:00  来源:igfitidea点击:

How to drag and drop a button from one panel to another panel?

c#winforms

提问by Ranjan Panigrahi

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.

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

Please suggest me a code.

请给我建议一个代码。

采纳答案by LarsTech

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;
}

回答by Jess Stuart

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

这种方法也适用于分组框,但必须手动添加 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
    // ...
}