65.9K
CodeProject is changing. Read more.
Home

Very simple way to move a form holding down mouse button

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Mar 15, 2011

CPOL
viewsIcon

7599

This method was converted to VB from C# but I believe to be much easier, althought it does not allow the F5 Key as yours does. Private panel1 As New Panel() Private canMove As Boolean Private currentPosition As Point Public Sub New() ...

This method was converted to VB from C# but I believe to be much easier, althought it does not allow the F5 Key as yours does.
        Private panel1 As New Panel()
        Private canMove As Boolean
        Private currentPosition As Point
        Public Sub New()
            Me.Controls.Add(panel1)
            panel1.Dock = DockStyle.Top
            panel1.BackColor = Color.Black
            Me.FormBorderStyle = FormBorderStyle.None
            AddHandler panel1.MouseDown, AddressOf panel1_MouseDown
            AddHandler panel1.MouseUp, AddressOf panel1_MouseUp
            AddHandler panel1.MouseMove, AddressOf panel1_MouseMove
        End Sub

        Private Sub panel1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs)
            If canMove Then
                Dim newPosition As Point = Control.MousePosition
                newPosition.X = newPosition.X - currentPosition.X
                newPosition.Y = newPosition.Y - currentPosition.Y
                Me.Location = newPosition
            End If
        End Sub

        Private Sub panel1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs)
            canMove = False
        End Sub

        Private Sub panel1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
            canMove = True
            currentPosition.X = e.X
            currentPosition.Y = e.Y
        End Sub