1 Year
Discussion Span
Last Post by TonyTGI

It's certainly possible. Create a form and put a few controls of any type on it. Then add the following code.

Public Class Form1

    Dim indrag As Boolean   'true while dragging control
    Dim startX As Integer   'x powition at drag start
    Dim startY As Integer   'y position at drag start

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'assign handlers for drag and drop to all controls

        For Each Control As Control In Me.Controls
            AddHandler Control.MouseDown, AddressOf startDrag
            AddHandler Control.MouseMove, AddressOf Dragging
            AddHandler Control.MouseUp, AddressOf endDrag

    End Sub

    Private Sub startDrag(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)

        'Mouse down - set drag active and save start position

        indrag = True
        startX = e.X
        startY = e.Y

    End Sub

    Private Sub Dragging(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)

        'move control to new position

        If indrag Then
            sender.Location = New Point(sender.Location.X + e.X - startX, sender.Location.Y + e.Y - startY)
        End If

    End Sub

    Private Sub endDrag(ByVal sender As System.Object, ByVal e As System.EventArgs)

        'Mouse up - set drag inactive

        indrag = False

    End Sub

End Class

This will allow you to reposition any control. If you only want to move specific controls then do AddHandler only for those controls.


If you need to save the positions of the controls from run to run then you can add a Settings variable. Name it ControlLocations and make it of type System.Collections.Specialized.StringCollection with an initial value of 0 (zero). Each entry in the collections consists of the control name, the control x position and the control y position. The fields are separated by !. Add the following to the form load event handler

For Each Control As Control In Me.Controls
    For Each item In My.Settings.ControlLocations
        If Split(item, "!")(0) = Control.Name Then
            Control.Location = New Point(Split(item, "!")(1), Split(item, "!")(2))
        End If

and you'll have to change the endDrag handler to save the new positions

indrag = False

For Each Control As Control In Me.Controls
    My.Settings.ControlLocations.Add(Control.Name & "!" & Control.Location.X & "!" & Control.Location.Y)


Edited by Reverend Jim

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.