1

This code i found i stackoverflow to move a borderless form in vb.net. I want to implement it for all the 10 forms of my project and don't want to put it in every form's code. Is there a way to use the single instance of this code for all forms? Thanks

Public Sub MoveForm_MouseDown(sender As Object, e As MouseEventArgs) Handles MyBase.MouseDown

    If e.Button = MouseButtons.Left Then
        MoveForm = True
        Me.Cursor = Cursors.NoMove2D
        MoveForm_MousePosition = e.Location
    End If

End Sub

Public Sub MoveForm_MouseMove(sender As Object, e As MouseEventArgs) Handles MyBase.MouseMove

    If MoveForm Then
        Me.Location = Me.Location + (e.Location - MoveForm_MousePosition)
    End If

End Sub

Public Sub MoveForm_MouseUp(sender As Object, e As MouseEventArgs) Handles MyBase.MouseUp

    If e.Button = MouseButtons.Left Then
        MoveForm = False
        Me.Cursor = Cursors.Default
    End If

End Sub
Saragis
  • 1,782
  • 6
  • 21
  • 30
Rahul Penn
  • 11
  • 1

1 Answers1

2

Make a derived class representing a borderless, movable form. Let this class inherit from the standard Form control and add in any additional functionality that you need. Use this new class instead of the standard Form when building forms.

Public Class MovableForm
    Inherits Form

Private MoveForm As Boolean
Private MoveForm_MousePosition As Point

Protected Overrides Sub OnMouseDown(e As MouseEventArgs)
    MyBase.OnMouseDown(e)

    If e.Button = MouseButtons.Left Then
        MoveForm = True
        Me.Cursor = Cursors.NoMove2D
        MoveForm_MousePosition = e.Location
    End If
End Sub

Protected Overrides Sub OnMouseMove(e As MouseEventArgs)
    MyBase.OnMouseMove(e)

    If MoveForm Then
        Me.Location += e.Location - MoveForm_MousePosition
    End If
End Sub

Protected Overrides Sub OnMouseUp(e As MouseEventArgs)
    MyBase.OnMouseUp(e)

    If e.Button = MouseButtons.Left Then
        MoveForm = False
        Me.Cursor = Cursors.Default
    End If
End Sub

End Class

Then to use it change the designer file of your form like this:

Partial Class Form1
    Inherits BorderlessForm
Saragis
  • 1,782
  • 6
  • 21
  • 30
  • You have the right idea, but if you "consume" the event in the base class then it is not appropriate to call the MyBase method. – Hans Passant Aug 29 '15 at 10:29