将图像拖放到多个框中

时间:2015-01-24 20:05:30

标签: vb.net

我的表单上有多个图片框,我希望能够将图像拖放到这些框中。为每一个写一个拖放都是多余的,所以我想写几个子并为每个盒分配处理程序。这是我做的:

Private Sub frmInventoryControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    For Each PicBox As PictureBox In Me.Controls.OfType(Of PictureBox)()

        PicBox.AllowDrop = True
        AddHandler PicBox.DragEnter, AddressOf picBoxs_DragEnter
        AddHandler PicBox.DragDrop, AddressOf picBoxs_DragDrop

    Next

End Sub

''' Drag and drop procedures to move pictures between
''' picture boxes
''' 

Private Sub picBoxs_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs)
    'Procedure to copy the dragged picture from the
    'open window

    If e.Data.GetDataPresent(DataFormats.FileDrop) Then

        'If the file explorer is open, copy the picture to the box
        e.Effect = DragDropEffects.Copy

    Else

        'otherwise, don't take action
        e.Effect = DragDropEffects.None

    End If
End Sub

Private Sub picBoxs_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs)

    'Procedure to select the pictue and drag to picturebox
    Dim picbox As PictureBox = CType(sender, PictureBox)
    Dim files() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())


    If files.Length <> 0 Then

        Try

            picbox.Image = Image.FromFile(files(0))
            picbox.Tag = files(0).ToString

        Catch ex As Exception

            MessageBox.Show("Image did not load")

        End Try

    End If
End Sub

如果我为每个特定的盒子编写代码,它可以正常工作,但如果尝试按照我上面的方式进行操作,则图像不会掉落。我的调试器没有给我一个错误,没有任何反应。我在哪里错了。

1 个答案:

答案 0 :(得分:1)

Me.Controls只能找到Form包含直接的PictureBox。如果它们位于不同的容器内,如Panel,则无法找到它们。在这种情况下,请将Me替换为该容器的名称,例如Panel1

更通用的解决方案是使用递归例程来查找所有PictureBox。如果相关的PictureBox位于多个容器中,这将特别有用:

Private Sub frmInventoryControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    FindAllPictureBoxes(Me)
End Sub

Private Sub FindAllPictureBoxes(ByVal container As Control)
    For Each c As Control In container.Controls
        If TypeOf c Is PictureBox Then
            Dim PicBox As PictureBox = DirectCast(c, PictureBox) 
            PicBox.AllowDrop = True
            AddHandler PicBox.DragEnter, AddressOf picBoxs_DragEnter
            AddHandler PicBox.DragDrop, AddressOf picBoxs_DragDrop
        ElseIf c.Controls.Count > 0 Then
            FindAllPictureBoxes(c)
        End If
    Next
End Sub