Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag & drop and get file path in VB.NET

I'd like to be able to drag a file/executable/shortcut into a Windows Forms 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 application and messagebox up the local path of the image.

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

like image 877
rabbitt Avatar asked Jul 27 '12 11:07

rabbitt


People also ask

What drag means in slang?

something/someone boring/annoying. something that slows progress. clothes of opposite sex.

What kind of person is a drag?

Drag is most commonly associated with gay men dressing up and embodying a “larger-than-life” female persona. Drag queens are flamboyant and this form of drag often involves sequins and feathers but it can also be sleek and edgy.

Why do they call it drag?

This definition probably originated in the theatre of the late 1800s, where male performers wore petticoats to perform as women. Their petticoats would drag on the floor, and so they referred to dressing up as women as “putting on their drags.”


2 Answers

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 DragEventArgs to receive the actual data and the GetData method


Example:

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
        MsgBox(path)
    Next
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
like image 55
sloth Avatar answered Sep 16 '22 14:09

sloth


This is just a note to state that if drag and drop does not work, it could be because you are running Visual Studio in Administrator Mode (Windows 7 and up I believe).

This also has to do with the UAC level currently set on your Windows installation.

like image 44
gouderadrian Avatar answered Sep 16 '22 14:09

gouderadrian