views:

39

answers:

2

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

A: 

You can call DoDragDrop with a data object containing or representing the control to begin a drag&drop operation, then handle the container's DragDrop event and move the control.

If you want to see the control as it's dragged, you can either make a transparent (handle WM_NCHITTEST) form under the mouse showing the control (call DrawToBitmap), or not use drag&drop at all and instead handle mouse events and track state manually.

If you want Visual Studio-style snaplines, you can compare the control's bounds to other controls, make a set of lines to draw, and draw them in a paint event.

SLaks
@Slaks: I can see on Panel and Button Control events. They dont have DoDragDrop event/Property. Do I have to AllowDrop to true.
Shantanu Gupta
Yes; you need to set `AllowDrop` on the container. `DoDragDrop` is a method that you need to call on MouseMove shortly after MouseDown if the mouse moved outside `SystemInformation.DragSize`.
SLaks
See the example here: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.dodragdrop.aspx
SLaks
@Slaks: Thx for help, Soon I will start with posting lots of questions on stack I think, :)
Shantanu Gupta
+1  A: 

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;
}
Johann Blais
that is the perfect solution
Shantanu Gupta