More Windows Secrets for Visual Basic, Page 4
Drag and Drop from Windows Explorer
Dragging and dropping within your application is pretty simple stuff. Simply set a couple of properties and you're rocking: look up 'drag and drop, Windows Forms' in the Help Index for more information. But what if you want to drag and drop from another application, such as Windows Explorer?
One of the most commonly requested, yet infrequently answered Windows form questions is, "How can I let my users drag and drop files and folders directly into my applications?". Simple, just follow these three easy steps:
- Change the AllowDrop property of the control you want users to drop the files onto to True. This could be a ListBox control, a Panel control, or even your form itself.
- Add code to the DragOver event of the control, so the typical 'copy' icon is displayed when files are dragged over:
- Finally, add code to the DragDrop event of the control, to receive and process information about the dropped files:
' As dragged over, check data is file drop If e.Data.GetDataPresent(DataFormats.FileDrop) Then ' Display the copy (or other) icon e.Effect = DragDropEffects.Copy End If
' Check this is a file drop If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then ' Retrieve list of files and loop through string array Dim strFiles() As String = e.Data.GetData( _ DataFormats.FileDrop) Dim intCount As Integer For intCount = 0 To strFiles.Length MessageBox.Show(strFiles(intCount)) Next End If
Of course, here we're simply displaying the dropped files or folders in a message box here; however, you could be doing something much more exciting: generating an MP3 play list; processing special work files; loading documents into your own mini word processor. The possibilities are endless.
Dragging and dropping from Windows Explorer
Page 4 of 5