图像拖放 - 如何获取图像

时间:2014-12-25 23:21:53

标签: vb.net image

我正在尝试编写一个程序,允许用户将图像从任何文件夹拖放到表单的图片框中。我得到了拖放部分,但我不知道如何将图像存储在变量上以便能够放在图片框上。以下是我到目前为止的情况:

    Public Sub New()


    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

    AddHandler picCategoryImage.DragDrop, AddressOf picCategoryImage_DragDrop
    AddHandler picCategoryImage.DragEnter, AddressOf picCategoryImage_DragEnter

End Sub

Private Sub picCategoryImage_DragDrop(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragDrop

    Dim picbox As PictureBox = CType(sender, PictureBox)
    Dim g As Graphics = picbox.CreateGraphics()

    g.DrawImage(CType(e.Data.GetData(DataFormats.Bitmap), Image), New Point(0, 0))


End Sub

Private Sub picCategoryImage_DragEnter(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragEnter

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

        e.Effect = DragDropEffects.Copy

    Else

        e.Effect = DragDropEffects.None

    End If


End Sub

我在哪里错了?

1 个答案:

答案 0 :(得分:3)

DragEnter 事件中需要DataFormats.FileDrop而不是DataFormats.Bitmap。在 DragDrop 中,打开从e.Data.GetData()获取的文件名:

Private Sub picCategoryImage_DragDrop(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles picCategoryImage.DragDrop
    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))
        Catch ex As Exception
            MessageBox.Show("Problem opening file ")
        End Try
    End If
End Sub

Private Sub picCategoryImage_DragEnter(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles picCategoryImage.DragEnter
    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        e.Effect = DragDropEffects.Copy
    Else
        e.Effect = DragDropEffects.None
    End If
End Sub

您还需要设置(在表单加载事件中):

picCategoryImage.AllowDrop = True