Drag label anywhere with the mouse,vb.net


' Generation Code...

Private cDragDrop As New NewControl

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    With cDragDrop
     .Location = New Point(20, 20)
     .Size = New Size(400, 300)
    End With
    Me.Controls.Add(cDragDrop)

End Sub

' Class Code
Public Class NewControl
    Inherits UserControl

    Dim CurrentPosition As New Rectangle(New Point(0, 0), New Size(50, 50))
    Dim Drag As Boolean = False
    Dim InitialClickPosition As Point

    Public Sub New()
        ' Initialise the class
        MyBase.New()
        ' Ensure appropriate elements are set
        Me.SetStyle(ControlStyles.UserPaint, True)
        Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        Me.SetStyle(ControlStyles.DoubleBuffer, True)

        Me.BackColor = Color.White
    End Sub

    ' This example assumes Imports System.Drawing
    Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs)
        Dim aBrush As New SolidBrush(Color.Red)
        pe.Graphics.FillEllipse(aBrush, CurrentPosition)
    End Sub

    Protected Overrides Sub OnMouseDown(ByVal e As System.Windows.Forms.MouseEventArgs)
        If e.X > Me.CurrentPosition.X AndAlso e.X <= (Me.CurrentPosition.X + Me.CurrentPosition.Width) AndAlso _
            e.Y > Me.CurrentPosition.Y AndAlso e.Y <= (Me.CurrentPosition.Y + Me.CurrentPosition.Height) Then
            InitialClickPosition = New Point(e.X - Me.CurrentPosition.X, e.Y - Me.CurrentPosition.Y)
            Drag = True
        End If
    End Sub

    Protected Overrides Sub OnMouseMove(ByVal e As System.Windows.Forms.MouseEventArgs)
        If Drag Then
            CurrentPosition.Location = New Point(e.X - Me.InitialClickPosition.X, e.Y - Me.InitialClickPosition.Y)
            Me.Invalidate()
        End If
    End Sub

    Protected Overrides Sub OnMouseUp(ByVal e As System.Windows.Forms.MouseEventArgs)
        Drag = False
    End Sub

    Private Sub InitializeComponent()
        Me.Name = "NewControl"
    End Sub
End Class