Answered move form by dragging control

  • Sunday, September 04, 2005 6:26 AM
     
     
    How can I move/reposition a form by dragging a control on that form with the mouse?

    I want to make a form with no boarder and a transparent background with a few progress bars on it. I want the user to be able to move the form by clicking and dragging one of the progress bars in the form

All Replies

  • Sunday, September 04, 2005 9:28 AM
     
     Answered
  • Monday, September 05, 2005 2:13 AM
    Moderator
     
     Answered

    Hi,

    Try my Pick and Drop method if it works for you:

    First, add this code to your Form:



    private bool _dragging = false;
    private Point _dragAt = Point.Empty;

    public void Pick(Control control, int x, int y)
    {
      _dragging = true;
      _dragAt = new Point(x,y);
      control.Capture = true;
    }

    public void Drop(Control control)
    {
      _dragging = false;
      control.Capture = false;
    }

     




    Then, handle your progress bar's MouseDown event, and add this code to the event method (the codes to be added to your event method is colored brown):



    private void MyProgressBar_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
    {
      Pick((Control)sender,e.X,e.Y);
    }

     


    Also handle your progress bar's MouseUp event, and add this code to the event method:



    private void MyProgressBar_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
    {
      Drop((Control)sender);
    }

     


    Finally, to make you progressbar able to drag the Form, handle the MouseMove event of your progress bar, and add this code to your event method:



    private void MyProgressBar_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
    {
      if (_dragging)
      {
        Left = e.X + Left - _dragAt.X;
        Top = e.Y + Top - _dragAt.Y;
      }
      else _dragAt = new Point(e.X,e.Y);

    }

     



    Good luck and happy coding,

    -chris