2015-07-10 53 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

也許你可以說一點關於你的代碼,其他人理解,不要只是複製。 –