Click to See Complete Forum and Search --> : Drag and Drop on a button?


irishman
May 30th, 2008, 11:35 AM
I have a form that allows users to move buttons around on the form, using the code below. I've noticed that, if you drag the button past the edge of the form, it disappears as if it has gone off the form and has kept going. It's no big deal if you hang on to the button. But if you drop it while it's off screen, I can't figure out how to bring it back. Does anyone know how to either place boundaries on the form or have code to return the button to its original position. Any help would be great.

Private _mouseDown As Boolean = False
Private _initialMouseX As Integer
Private _initialMouseY As Integer

Private Sub Button1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseDown
_mouseDown = True;
_initialMouseX = e.X;
_initialMouseY = e.Y;
End Sub

Private Sub Button1_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseUp
_mouseDown = False;
End Sub

Private Sub Button1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseMove
If ( Not _mouseDown) Then Return
Dim deltaX As Integer = e.X - _initialMouseX
Dim deltaY As Integer = e.Y - _initialMouseY
Button1.Left += deltaX
Button1.Top += deltaY
End Sub

Marraco
May 30th, 2008, 12:38 PM
... Does anyone know how to either place boundaries on the form or have code to return the button to its original position.You can limit the cursor freedom of movement with the function
Private Declare Function ClipCursor Lib "user32" (ByRef lpRect As Rectangle) As Integer
Rectangle is a System.Drawing.Rectangle type.

Example:
(On Mouse down event)
Dim Restriction As System.Drawing.Rectangle = New Rectangle(X,Y,Width,Height)
ClipCursor(Restriction)
Maybe VB.NET have a built in solution for limiting mouse movement. I don't know it.
_