2015-07-10 44 views
0

我正试图在面板中移动图片框。如何使用vb.net在面板中移动图片框

这是我的代码:

Private dragging As Boolean 
Private beginX, beginY As Integer 

Private Sub Control_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) 
     dragging = True 
     beginX = CType(sender, PictureBox).Location.X 
     beginY = CType(sender, PictureBox).Location.Y 
End Sub 

Private Sub Control_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) 
     Dim cntrl As Control = CType(sender, Control) 
     If dragging = True Then 
      cntrl.Location = New Point(cntrl.Location.X + e.X - beginX, cntrl.Location.Y + e.Y - beginY) 
      'Me.Refresh() 
     End If 
End Sub 

Private Sub Control_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) 
     dragging = False 
End Sub 

我想不通为什么这不工作。

回答

0

您所拥有的子程序最后缺少它们的处理程序(即handles语句)。

例如:

Private Sub Control_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) HANDLES controlName.MouseUp 
    dragging = False 
End Sub 
+0

我在循环 for循环 BTN =新的PictureBox 的AddHandler btn.MouseUp,AddressOf Control_MouseUp AddHandler的BTN创建图片框。 MouseDown,AddressOf Control_MouseDown AddHandler btn.MouseMove,AddressOf Control_MouseMove pnlLocker.Controls.Add(btn) 下一个 – ram

+0

您应该编辑您的问题以包含该代码。 –

+0

每当我点击图片框它闪烁,当我移动鼠标的图片框不会改变它的位置... – ram

0

试试这个:

Dim cmd As Boolean = False  
    Dim sp As Point 
    Private Sub Form1_Load() Handles MyBase.Load 
     For Each Control As Picturebox In Me.Controls.OfType(Of Picturebox) 
     AddHandler Control.MouseDown, Sub(sender As Object, e As MouseEventArgs) 
              cmd = True 
              sp = e.Location 
             End Sub 
     AddHandler Control.MouseMove, Sub(sender As Object, e As MouseEventArgs) 
              If cmd Then 
               Control.Location = Control.Location - sp + e.Location 
              End If 
             End Sub 
     AddHandler Control.MouseUp, Sub(sender As Object, e As MouseEventArgs) 
             cmd = False 
            End Sub 
     Next 
    End Sub 
+0

也许你可以说一点关于你的代码,其他人理解,不要只是复制。 –