VB.Net: How to make a borderless WinForm draggable


Scenario:

You have a borderless form in a Windows Forms application and you want to make it moveable by being able to click on it and drag it. By default, borderless forms cannot be moved without intervention since most Windows require that you click on the title bar (which is hidden in this case). With a few Windows API's we can make this happen. In this example, I just created a stock Windows application project, changed the FormBorderStyle property to none and then put the following code into my form:

VB.Net

Imports System.Runtime.InteropServices

Public Class Form1

    Public Const WM_NCLBUTTONDOWN As Integer = &HA1
    Public Const HT_CAPTION As Integer = &H2

    <DllImportAttribute("user32.dll")> _
    Public Shared Function SendMessage(hWnd As IntPtr, Msg As Integer, wParam As Integer, lParam As Integer) As Integer
    End Function

    <DllImportAttribute("user32.dll")> _
    Public Shared Function ReleaseCapture() As Boolean
    End Function

    Private Sub Form1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
        If e.Button = MouseButtons.Left Then
            ReleaseCapture()
            SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0)
        End If
    End Sub

End Class