In this tutorial lets see as how we can move the controls at run time. This can be applied to any control. Here I took one Label, one TextBox and one Button.
Start a Windows application and add a Label, Button and TextBox to the form. Then Create 3 methods to handle MouseDown, MouseMove and MouseUp events of the controls. You can easily do this by just selecting this event for any of the control you have added and then add the other controls names also at the Handles part. The functions will look as below...
Private Sub ControlMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseDown, Label1.MouseDown, TextBox1.MouseDown
End Sub
Private Sub ControlMouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseMove, Label1.MouseMove, TextBox1.MouseMove
End Sub
Private Sub ControlMouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseUp, Label1.MouseUp, TextBox1.MouseUp
End Sub
Later you need to write few lines of code... Complete code is given below.
'' Declare Two Public Variables
Dim isDragged As Boolean = False Dim ptStartPosition As Point
Private Sub ControlMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseDown, Label1.MouseDown, TextBox1.MouseDown
Dim ctrlTemp As Control = sender
If e.Button = Windows.Forms.MouseButtons.Left Then
isDragged = True
ptStartPosition = New Point(Me.MousePosition.X- Me.Location.X - 4, Me.MousePosition.Y- Me.Location.Y - 30)
ctrlTemp.Location = ptStartPosition Else
isDragged = False
End If
End Sub
Private Sub ControlMouseMove(ByVal sender As Object,ByVal e As System.Windows.Forms.MouseEventArgs) HandlesButton1.MouseMove, Label1.MouseMove, TextBox1.MouseMove
Dim ctrlTemp As Control = sender
Dim ptEndPosition As Point
If isDragged Then
ptEndPosition = New Point(Me.MousePosition.X- Me.Location.X - 4 - (ctrlTemp.Size.Width /2), Me.MousePosition.Y - Me.Location.Y - 30 - (ctrlTemp.Size.Height / 2))
ctrlTemp.Location = ptEndPosition
End If
End Sub
Private Sub ControlMouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseUp, Label1.MouseUp, TextBox1.MouseUp
isDragged = False
End Sub
This will do the work.... Now you can change the position of the control at any time. You can save the position in some configuration file so that the position will be saved even after restarting the application.