Drag and Drop files from Windows to your application


While working around an Script Editor application, I found that in almost all the editors we can drag and drop files from Windows.(Even MS Notepad supports it.) Then I searched for an implementation, but unfortunately I can’t find a perfect one. Then I thought of implementing the same. I am not sure this one is a perfect implementation or not, but it works fine for me. :)

Here is the code. Seems like it is self explanatory

Imports System.IO
Public Class frmMain

    Private Sub txtEditor_MouseDown(ByVal sender As System.Object, _
                                    ByVal e As System.Windows.Forms.MouseEventArgs) _
                                    Handles txtEditor.MouseDown
        'Initiating the Drag and Drop
        txtEditor.DoDragDrop("", DragDropEffects.Copy)
    End Sub

    Private Sub txtEditor_DragEnter(ByVal sender As System.Object, _
                                    ByVal e As System.Windows.Forms.DragEventArgs) _
                                    Handles txtEditor.DragEnter
        'Ensures the dragging data is valid type.
        'Then only setting the drop effect.
        'Otherwise you will see no drop cursor, instead of Copy
        If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
            e.Effect = DragDropEffects.Copy
            e.Effect = DragDropEffects.None
        End If

    End Sub

    Private Sub txtEditor_DragDrop(ByVal sender As System.Object, _
                                   ByVal e As System.Windows.Forms.DragEventArgs) _
                                   Handles txtEditor.DragDrop
        'Getting the filename.
        'The length of files array will be based on the number of files dragging.
        Dim files As String() = e.Data.GetData(DataFormats.FileDrop)
        'Checking the files(0) is Sql File.
        If Path.GetExtension(files(0)).Equals(".sql", _
                                              StringComparison.CurrentCultureIgnoreCase) Then
            'Reading it using Stream reader
            Me.Text = String.Format("Drag Drop demo - {0}", _
            Using sr As New StreamReader(files(0))
                Me.txtEditor.Text = sr.ReadToEnd
            End Using
            'Otherwise displaying message box
            MessageBox.Show("Only supports SQL files")
        End If
    End Sub
End Class

Here is the screen shot

Drag and Drop Demo - Screenshot

Drag and Drop Demo - Screenshot

If some one know a better implementation please let me know.

More details from MSDN :Performing Drag-and-Drop Operations in Windows Forms

Anuraj is currently working as Technical Lead. He is a regular speaker on Technology events. He has more than 11+ years experience with Microsoft.Net Technologies.

Facebook Twitter LinkedIn Google+