如何允许用户在他选择的位置拖动动态创建的控件

Sha*_*pta 11 c# controls draggable winforms

我正在创建一个应用程序,我需要生成动态创建的控件,如文本框或标签等.

现在我该用户可以将该文本框重新定位到他想要的位置.就像我们在Visual Studio中一样.一种方法是通过使用文本框从他那里获取值来获取新位置.但我希望用户界面容易.

我们能否在winforms中拥有此类功能

Joh*_*ais 23

我创建了一个简单的表单,演示如何通过拖动控件来移动控件.该示例假定在附加到相关事件处理程序的表单上有一个名为button1的按钮.

private Control activeControl;
private Point previousLocation;

private void button1_Click(object sender, EventArgs e)
{
    var textbox = new TextBox();
    textbox.Location = new Point(50, 50);
    textbox.MouseDown += new MouseEventHandler(textbox_MouseDown);
    textbox.MouseMove += new MouseEventHandler(textbox_MouseMove);
    textbox.MouseUp += new MouseEventHandler(textbox_MouseUp);

    this.Controls.Add(textbox);
}

void textbox_MouseDown(object sender, MouseEventArgs e)
{
    activeControl = sender as Control;
    previousLocation = e.Location;
    Cursor = Cursors.Hand;
}

void textbox_MouseMove(object sender, MouseEventArgs e)
{
    if (activeControl == null || activeControl != sender)
        return;

    var location = activeControl.Location;
    location.Offset(e.Location.X - previousLocation.X, e.Location.Y - previousLocation.Y);
    activeControl.Location = location;
}

void textbox_MouseUp(object sender, MouseEventArgs e)
{
    activeControl = null;
    Cursor = Cursors.Default;
}
Run Code Online (Sandbox Code Playgroud)