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

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.

Blake
Blake - Tuesday, May 24, 2022

@Boyd Glad to hear it helped!

Boyd Evan White
Boyd Evan White - Thursday, May 19, 2022

Wow, very simple and straight forward code. Implemented perfectly without issue in a VB.NET Visual Studio 2019 Community edition project. Using it on two forms without borders and Ruler graphics on both forms. Forms are sync so that when one is dragged the other Form (e.g. Ruler) moves in sync. Using this for Document QC'ing with the PDF on one side and the converted product on the other. Thanks very much for putting this snippet out there!