C# - Moving a control to the mouse's position
c#, controls, flicker, mouse, position
Solution
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 `if`s in this code to `while`s, as it will make a difference.
Problem
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!