2015-01-13 96 views
0

我有一个拖放事件来将图像放入图片框中。我需要获取图像位置以便存储在我的数据库中。如果我使用OpenFileDialog,我可以获取位置,但如果使用拖放,我似乎无法获取它。这里是我的代码:使用拖放获取图像位置

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


    '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 
     picCategoryImage.BorderStyle = BorderStyle.FixedSingle 
     TextBox1.Text = picCategoryImage.ImageLocation 

    Else 

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

    End If 


End Sub 

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

    '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)) 
      btnDeleteImage.Visible = True 
      picbox.BorderStyle = BorderStyle.None 
      picCategoryImage.BringToFront() 
      btnDeleteImage.BringToFront() 


     Catch ex As Exception 

      MessageBox.Show("Image did not load") 

     End Try 

    End If 

End Sub 
+1

'文件(0)'(在放置事件中)是文件名,也许调用一个过程在最后传递它作为参数保存? – Plutonix

回答

1

至于建议的Plutonix,你已经在使用的文件路径,所以你已经知道了。这就是Image.FromFile能够如何从文件创建Image。如果你的意思是,你需要能够得到的路径后,那么你有两个主要选择:

  1. 随你正在做的和路径存储以备后用一个成员变量。

  2. 与其说Image.FromFile和设置PictureBoxImage的,只需调用PictureBoxLoad方法。然后您可以从ImageLocation属性中获取路径。

我实际上会建议使用选项2,因为它具有不会像当前代码那样锁定文件的额外优势。