4

I create a new Windows Forms Application. I drag a button on to the form. I need to drag and drop this button to another location within this form at run time. any code snippets or links are appreciated.

I spent half an hour searching before coming here.

CodingJoy
  • 95
  • 1
  • 1
  • 8

1 Answers1

11

You can start with something like this:

  bool isDragged = false;
  Point ptOffset;
  private void button1_MouseDown( object sender, MouseEventArgs e )
  {
     if ( e.Button == MouseButtons.Left )
     {
        isDragged = true;
        Point ptStartPosition = button1.PointToScreen(new Point(e.X, e.Y));

        ptOffset = new Point();
        ptOffset.X = button1.Location.X - ptStartPosition.X;
        ptOffset.Y = button1.Location.Y - ptStartPosition.Y;
     }
     else
     {
        isDragged = false;
     }
  }

  private void button1_MouseMove( object sender, MouseEventArgs e )
  {
     if ( isDragged )
     {
        Point newPoint = button1.PointToScreen(new Point(e.X, e.Y));
        newPoint.Offset(ptOffset);
        button1.Location = newPoint;
     }
  }

  private void button1_MouseUp( object sender, MouseEventArgs e )
  {
     isDragged = false;
  }
msergeant
  • 4,771
  • 3
  • 25
  • 26
  • Thanks for your response. I tried this but the button still just sits there at its original location. I moved the code in MouseMove handler in MouseUp handler and now the button moves to new location. the new location is bit erratic. need to figure out that part. but thanks again for your help – CodingJoy Sep 16 '10 at 19:00
  • The erratic location is probably due to the offset. You get mouse coordinates in a different format than the screen coordinates of the location. That's the reason for the calls to PointToScreen. – msergeant Sep 17 '10 at 11:26
  • @msergeant Excellent example, works great! However I am experiencing a flickering tail when I drag the button around. Any idea what could be causing that? – Maritim Nov 19 '13 at 10:56
  • I found the solution in http://stackoverflow.com/questions/2612487/how-to-fix-the-flickering-in-user-controls :) – Maritim Nov 19 '13 at 11:00