Drag and Drop files from Windows to your application
July 4th, 2009
No comments
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
Else
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}", _
Path.GetFileNameWithoutExtension(files(0)))
Using sr As New StreamReader(files(0))
Me.txtEditor.Text = sr.ReadToEnd
End Using
Else
'Otherwise displaying message box
MessageBox.Show("Only supports SQL files")
End If
End Sub
End Class
Here is the screen shot
If some one know a better implementation please let me know.
More details from MSDN :Performing Drag-and-Drop Operations in Windows Forms
Categories: .Net, .Net 3.0 / 3.5, Visual Studio, Windows Forms .Net, Drag and Drop, Drag Drop, VB.Net, Windows Forms

