How to allow user to drag a dynamically created control at the location of his choice

Shantanu Gupta picture Shantanu Gupta · Oct 6, 2010 · Viewed 17.5k times · Source

I am creating an application where I need to generate dynamically created controls say textbox or label etc.

Now what I that user can relocate that textbox to his desired location. Like we do in Visual Studio. One way is to get new location by getting values from him using textbox. But I want the user interface easy.

Can we have such functionality in winforms

Answer

Johann Blais picture Johann Blais · Oct 6, 2010

I have created a simple form that demonstrate how to move the control by dragging the control. The example assumes there is a button named button1 on the form attached to the relevant event handler.

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