Control cntd. and Conclusion
So not big bad evil code really but worth explaining. For the mousedown event
we set our form level boolean, Dragging, to True. We record the mouse x and
y position as the negative values of the mouseeventargs e.x and e.y respectively.
This is because they will be used to Offset (subtract the current x and y by
the original position when mousedown occurred) the mouseposition in the mousemove
event. I then calculate the area which we will allow the button to move. This
has to be the client left, right, top and bottom co-ordinates of the form.
For example the clipleft is the client x position of the mouse (distance of
the mouse from the left of the screen) less the x position of the button on
the form. This should give a current x value for the location of the form. I'm
sure there is a better way of doing this because as you'll see if you try the
example the four clip values I calculate are far from perfect and as ever I'm
open to anyone giving me a better way of doing it. A job for another day perhaps.
These values are then used to set the clip of the cursor (which limits mouse
movement to the rectangle specified). The final line in that procedure is btnMove.Invalidate
which causes it to be repainted on the form.
The mousemove event creates a point from the current mouse position, Me.PointToClient(MousePosition),
then Offsets by subtracting the x and y values we saved. They are subtracted
because they were set as negative values. The button's location is then changed
to this new point. Finally for the mouseup event the Dragging boolean is set
to false, the clip is set to nothing which releases the mouse again and the
button is invalidated for repainting. If you try this you'll se it works a treat
for the most part. I'm pretty sure you could improve upon this but as with so
many things in this article it's a start.
Conclusion
Drag and Drop is one of those cool things which is easier done than most think
as you will have seen here. It's origins are based on improving the user experience
and anything that makes our users happier is worth incorporating. I hope you
can make some sense of this article and use it to make your users happier. Remember,
though, to apply the Scotty rule by overestimating how difficult something is
and how long it will take so that when they finally can drag and drop they'll
think it's just as cool as you do and pay you more hopefully.