rabbitt rabbitt - 1 year ago 348
Vb.net Question

VB.net - drag & drop and get file path?

I'd like to be able to drag a file/executable/shortcut into a windows form application and have the application determine the original path of the dropped file then return it as a string?

E.g. drag an image from the desktop into the app and messagebox up the local path of the image.

Is that possible? Could someone provide me with an example maybe?


Answer Source

It's quite easy. Just enable drap-and-drop by setting the AllowDrop property to True and handle the DragEnter and DragDrop events.

In the DragEnter event handler, you can check if the data is of the type you want using the DataFormats class.

In the DragDrop event handler, use the Data property of the DataEventArgs to recieve the actual data.


Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Me.AllowDrop = True
End Sub

Private Sub Form1_DragDrop(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
    Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
    For Each path In files
End Sub

Private Sub Form1_DragEnter(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter
    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        e.Effect = DragDropEffects.Copy
    End If
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download