2014-12-25 234 views
0

我想寫一個程序,允許用戶將圖像從任何文件夾拖放到窗體的圖片框中。我得到了拖放部分,但我不知道如何將圖像存儲在變量上,以便能夠將其放置在圖片框上。這是我到目前爲止:圖像拖放 - 如何獲取圖像

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 

我在哪裏錯了?

+0

你怎麼從任意文件夾中的意思是'圖像'你的意思是*文件*恰好是圖像文件嗎?如果它是一個真實的圖像,它來自哪裏/它是如何被丟棄的? – Plutonix

回答

2

您需要DataFormats.FileDrop而不是DataFormats.BitmapDragEnter事件。而在的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