Drag and move controls in runtime


December 18, 2008
Feedback's a good way to encourage author even if it's a criticize. It's proved you care about the article. Please, leave a comment to let everyone know what you think about this post.

another tip »

Simple, you have a control in a form and you want to move it around like you could move the icons in your desktop.

[more]
For preparation, create a from with a control, say a button.
Declare System.Drawing.Point StartPosition and System.Drawing.Point OldPosition

System.Drawing.Point OldPosition;

Select the button and click on the Events button.
Double click on MouseDown to create a new event for the button.
What we do here is when user put the mouse down on the button, we prepare for that object to move:

private void Button1_MouseDown(object sender, MouseEventArgs e)
{
    //Only prepare if the button click down is the left button
    if (e.Button == MouseButtons.Left)
    {
        //Store the current mouse location
        OldPosition = e.Location;
        //Change the mouse cursor if you want
        Button1.Cursor = Cursors.NoMove2D;
    }
}

Now add new event MouseMove for that button. So if user move the mouse with the left button still click on top of the button, move the control follow the mouse.

private void Button1_MouseMove(object sender, MouseEventArgs e)
{
    //Only move if the left button still down
    if (e.Button == MouseButtons.Left)
    {
        Button1.Location = new Point(Button1.Location.X + (e.X - OldPosition.X), Button1.Location.Y + (e.Y - OldPosition.Y));
    }
}

That's it. Your control could be movable now.

Have fun!

  • Delicious

Some more useful articles for you

Under Category: Algorithm, App Development
Article Tags: ,
Leave a Reply