将图像拖放到多个框中

Drag and drop images to multiple boxes

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

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

如果我为每个特定的框编写代码,它就可以工作,但如果按照我上面的方法尝试,图像不会丢失。我的调试器没有给我错误,只是什么也没发生。我哪里错了。

Me.Controls 只会找到 直接 包含在表单中的图片框。如果它们位于不同的容器内,例如面板,则将找不到它们。在这种情况下,将 Me 替换为该容器的名称,例如 Panel1.

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

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