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

时间:2015-05-31 16:00:00

标签: winforms user-controls runtime

我使用以下代码在运行时创建按钮但如何使它们可移动(可在任何地方使用鼠标拖动)

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

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

1 个答案:

答案 0 :(得分:0)

由于鼠标在拖动时可以移动到按钮之外,因此您必须使用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);
    }
}