Going over code that doesn't work for you line-by-line is generally a waste of time.
What's important is for you to analyze the code and understand what it does ... or doesn't do ... now.
Take the example using MouseDown and MouseMove: when you do this:
this.location = e.location;
Then you are saying: make the top-left corner of the Control that is receiving the MouseMove Event be positioned where the Mouse is now on the Control. Remember that what e.Location returns are co-ordinates based on the Control, not co-ordinates of a Location on the Form ! So, if e.Location reports you are at 100,100, you will set the Location of the Control to 100,100 in Form co-ordinates !
The WndProc example is just a mistake; and I'd forget about it: there are working WndProc solutions that will do this, like: [
^], but, in this simple case you don't need them.
Example:
1. set a boolean flag to 'true when the Mouse goes down in the Control; set it to 'false when the Mouse is up.
a. when the Mouse goes down set two integer variables mx,my to the e.X and e.Y of the MouseDown handler. This records the location on the Control where the Mouse went down, in Control co-ordinates.
2. in the MouseMove EventHandler:
a. if the Mouse is up ... based on the value of the flag ... exit
b. if the Mouse is down:
1. create a horizontal offset based on the subtracting the initial value of the Mousedown mx from the current mouse location e.X; create a similar vertical offset.
2. add the horizontal offset to the 'Left property of the Control; add the vertical offset to the 'Top property.
private bool isMouseUp = true;
private int mx, my;
private void SomeControl_MouseDown(object sender, MouseEventArgs e)
{
isMouseUp = false;
mx = e.X;
my = e.Y;
}
private void SomeControl_MouseUp(object sender, MouseEventArgs e)
{
isMouseUp = true;
}
private void SomeControl_MouseMove(object sender, MouseEventArgs e)
{
if(isMouseUp) return;
SomeControl.Left += e.X - mx;
SomeControl.Top += e.Y - my;
}
Now this is really simple stuff ... when you understand the difference between Control co-ordinates, and Form (or other Container Control) co-ordinates.
To make this more interesting, I challenge you to figure out how ... when the user moves the Control, or Form ... to always make sure all of its area is on-screen, or within the bounds of its Container Control. Hints: ClientRectangle, Rectangle.Intersect.