Drag and move controls in runtime


December 18, 2008
Don't know what to read next? Check out the list of popular posts. People like them, they should be good.

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!

Share
Under Category: Algorithm, App Development
Article Tags: ,
June 4th, 2011

hi.. check this … it’s quite easy this way…

http://winform-net.blogspot.com/2011/06/simple-class-for-moving-controls-at.html

just sharing.. :)

Trackbacks
Leave a Reply