title: Move Panel around Panel with Background Image
body: <p>I'm trying to build a windows application in VB.Net as part of the application I need to be able to place markers on and image but I'm having a large number of problems.</p>
  
  <p>I have a panel which I have assigned the image I want to place markers on as the background and then I add custom panels to the panel.</p>
  
  <p>The custom panel containing an image (the marker) and a label (the marker name) as I though moving just the panel would be easier than moving the marker image and name label.</p>
  
  <p>I've tried assigning event handlers to the MouseDown, MouseUp and MouseMove to each of the custom panels but every time I try and move the panel it goes all over the place and leaves black boxes everywhere.</p>
  
  <pre><code>Dim image As New System.Drawing.Bitmap(/* Path */)
  pnlPreviewPanel.BackgroundImageLayout = ImageLayout.Stretch
  pnlPreviewPanel.BackgroundImage = image
  
  pnlPreviewPanel.Controls.Clear()
  For Each item As Marker In mMarkers
      Dim panel as New CustomPanel
  
      AddHandler panel, AddressOf DeviceMouseDown
      AddHandler panel.Controls(0).MouseDown, AddressOf DeviceMouseDown
      AddHandler panel.Controls(1).MouseDown, AddressOf DeviceMouseDown
  
      AddHandler panel.MouseUp, AddressOf DeviceMouseUp
      AddHandler panel.Controls(0).MouseUp, AddressOf DeviceMouseUp
      AddHandler panel.Controls(1).MouseUp, AddressOf DeviceMouseUp
  
      AddHandler panel.MouseMove, AddressOf DeviceMouseMove
      AddHandler panel.Controls(0).MouseMove, AddressOf DeviceMouseMove
      AddHandler panel.Controls(1).MouseMove, AddressOf DeviceMouseMove
  
      pnlPreviewPanel.Controls.Add(panel)
  Next
  
  Private Sub DeviceMouseDown(ByVal pSender As Object, ByVal pEventArgs As MouseEventArgs)
      Dim control As Control = pSender
      If Not control.GetType() = GetType(CustomPanel) Then
          control = control.Parent
      End If
  
      mSelectedPanel = CType(control, CustomPanel)
  End Sub
  
  Private Sub DeviceMouseUp(ByVal pSender As Object, ByVal epEventArgs As MouseEventArgs)
      If Not mSelectedDevicePanel Is Nothing Then
          mSelectedDevicePanel = Nothing
      End If
  End Sub
  
  Private Sub DeviceMouseMove(ByVal pSender As Object, ByVal pEventArgs As MouseEventArgs)
      If Not mSelectedDevicePanel Is Nothing Then
          Dim x As Integer = pEventArgs.Location.X - pnlPreviewPanel.Location.X
          Dim y As Integer = pEventArgs.Location.Y - pnlPreviewPanel.Location.Y
  
          mSelectedDevicePanel.Location = New Point(x, y)
      End If
  End Sub
  </code></pre>