Understandably this is old, but I ran across this post while looking to do the same thing. I thought there might be an actual drag event, but I guess not. Here's how I did it.
Private Sub ContainerToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ContainerToolStripMenuItem.Click
Dim pnl As New Panel
pnl.Size = New Size(160, 160)
pnl.BackColor = Color.White
AddHandler pnl.MouseDown, AddressOf Control_DragEnter
AddHandler pnl.MouseUp, AddressOf Control_DragLeave
AddHandler pnl.MouseMove, AddressOf Control_Move
Me.Controls.Add(pnl)
End Sub
Private Sub Control_DragEnter(ByVal sender As Object, ByVal e As EventArgs)
MouseDragging = True
End Sub
Private Sub Control_DragLeave(ByVal sender As Object, ByVal e As EventArgs)
MouseDragging = False
End Sub
Private Sub Control_Move(ByVal sender As Object, ByVal e As EventArgs)
If MouseDragging = True Then
sender.Location = Me.PointToClient(Control.MousePosition)
End If
End Sub
The ContainerToolStripMenuItem
is from my ToolStrip that adds a Panel on-the-fly. MouseDragging
is class level. Drags like a charm. Also, don't use Cursor.Position
as it will return the position relative to your entire Window, not the Form (or whatever container it is you're in).