Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag and Drop Windows Forms Button

Tags:

winforms

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.

like image 572
CodingJoy Avatar asked Dec 21 '22 23:12

CodingJoy


1 Answers

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;
  }
like image 108
msergeant Avatar answered Jan 18 '23 03:01

msergeant