views:

394

answers:

1

Hello everybody. I am trying to get a control to follow the cursor when the user clicks and drag the control. The problem is that 1.) the control doesn't go to the mouse's position, and 2.) the control flickers and flies all over the place. I've tried a few different methods of doing this, but all so far have failed.

I've tried:

protected override void OnMouseDown(MouseEventArgs e)
{
     while (e.Button == System.Windows.Forms.MouseButtons.Left)
     {
          this.Location = e.Location;
     }
}

and

protected override void OnMouseMove(MouseEventArgs e)
{
     while (e.Button == System.Windows.Forms.MouseButtons.Left)
     {
          this.Location = e.Location;
      }
}

but neither of these work. Any help is appreciated, and thanks in advance!

+2  A: 

Here's how to do it:

private Point _Offset = Point.Empty;

protected override void MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        _Offset = new Point(e.X, e.Y);
    }
}

protected override void MouseMove(object sender, MouseEventArgs e)
{
    if (_Offset != Point.Empty)
    {
        Point newlocation = this.Location;
        newlocation.X += e.X - _Offset.X;
        newlocation.Y += e.Y - _Offset.Y;
        this.Location = newlocation; 
    }
}

protected override void MouseUp(object sender, MouseEventArgs e)
{
    _Offset = Point.Empty;
}

_Offset is used here for two purposes: keeping track of where the mouse was on the control when you initially clicked it, and also keeping track of whether the mouse button is down or not (so that the control doesn't get dragged when the mouse cursor goes over it and the button isn't down).

You definitely don't want to switch the ifs in this code to whiles, as it will make a difference.

MusiGenesis
I've tried this and it doesn't make a difference. I appreciate the effort though.
APShredder
+1:MusiGenesis' code works for me like a charm, but with a little modification: I created a new user control -> override the three methods OnMouseDown, OnMouseUp, and OnMouseMove -> the first line in each of these methods is a call to the base method, that is base.OnMouseDown(e), base.OnMouseMove(e), and base.OnMouseUp(e). -> the rest of the code goes as MusiGenesis discussed.
Sameh Serag
Thank you so much! This new answer works like a charm! I truly appreciate it!
APShredder