如何在运行时创建可移动(通过鼠标)按钮 C#

How to create moveable (by mouse) buttons at runtime c#

我正在使用以下代码在 运行 时创建按钮,但如何使它们可移动(可在屏幕上的任何位置用鼠标拖动)

var b = new Button();
    b.Text = "My Button";
    b.Name= "button"; 
    b.Click += new EventHandler(b_Click);
    b.MouseUp += new MouseEventHandler(this.b_MouseUp);
    b.MouseDown += new MouseEventHandler(this.b_MouseDown);
    b.MouseMove += new MouseEventHandler(this.b_MouseMove);
    this.myPanel.Controls.Add(b);

我尝试使用鼠标事件,但无法使它们根据鼠标指针移动

由于鼠标在拖动时可以移到按钮外,因此您必须使用Control.Capture 属性。
此示例让您不在整个屏幕上移动按钮,而是在其父容器的边界内(或在其外部,然后隐藏,这可能应该被阻止)。

private Point Origin_Cursor;
private Point Origin_Control;
private bool BtnDragging = false;

private void button1_Click(object sender, EventArgs e)
{
    var b = new Button();
    b.Text = "My Button";
    b.Name = "button";
    //b.Click += new EventHandler(b_Click);
    b.MouseUp += (s, e2) => { this.BtnDragging = false; };
    b.MouseDown += new MouseEventHandler(this.b_MouseDown);
    b.MouseMove += new MouseEventHandler(this.b_MouseMove);
    this.panel1.Controls.Add(b);
}

private void b_MouseDown(object sender, MouseEventArgs e)
{
    Button ct = sender as Button;
    ct.Capture = true;
    this.Origin_Cursor = System.Windows.Forms.Cursor.Position;
    this.Origin_Control = ct.Location;
    this.BtnDragging = true;
}

private void b_MouseMove(object sender, MouseEventArgs e)
{
    if(this.BtnDragging)
    {
        Button ct = sender as Button;
        ct.Left = this.Origin_Control.X - (this.Origin_Cursor.X - Cursor.Position.X);
        ct.Top = this.Origin_Control.Y - (this.Origin_Cursor.Y - Cursor.Position.Y);
    }
}