Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirsbo/e900065bd6993d87d560 to your computer and use it in GitHub Desktop.
Save kirsbo/e900065bd6993d87d560 to your computer and use it in GitHub Desktop.
VB.NET Winforms - Making form with formBorderStyle=none draggable

Authored in 2010

When building UI's for desktop applications in Winforms, you occassionally need full graphical control of the form. The default form with a title bar is thus not suitable. Setting the formBorderStyle property of forms to none, means it no longer has a top title bar, thereby giving full graphical control of the window.

A common problem with this however, is that the user can no longer move the form by dragging it's titlebar around the screen (as the titlebar has been hidden).

The following code is a workaround that allows forms to be dragged around, like with any usual application. It has to be entered in the code-behind for the form for which you want to enable dragging.

Private IsFormBeingDragged As Boolean = False
Private MouseDownX As Integer
Private MouseDownY As Integer
 
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseDown
If e.Button = MouseButtons.Left Then
IsFormBeingDragged = True
MouseDownX = e.X
MouseDownY = e.Y
End If
End Sub
 
Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseUp
If e.Button = MouseButtons.Left Then
IsFormBeingDragged = False
End If
End Sub
 
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseMove
 
If IsFormBeingDragged Then
Dim newLocation As Point = New Point()
 
newLocation .X = Me.Location.X + (e.X - MouseDownX)
newLocation .Y = Me.Location.Y + (e.Y - MouseDownY)
Me.Location = newLocation
newLocation = Nothing
End If
End Sub

If you have a lot of forms in your application that are all with formBorderStyle=none, it's a good idea to subclass the Windows form class and overridde methods for MouseDown, MouseUp and MouseMove.

@byronbytes
Copy link

yay! ty

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment