作 者:MSDN
引用自:http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vbtchimpdragdrop.asp
Dragging Files
Drag and drop is used pervasively in Windows for moving or copying files. Windows Explorer fully supports drag and drop, and for many users this is the preferred method of working with files. In addition, many users are accustomed to dropping files onto an application to open them — for example, dragging and dropping a .doc file onto Microsoft Word.
In this example drag and drop is used to populate a ListBox control with a list of files dragged from Windows Explorer.
To enable drag and drop for a file
1. Add a ListBox control to a form and set its AllowDrop property to True.
2. Add the following code:
Private Sub ListBox1_DragEnter(ByVal sender As Object, ByVal e As _ System.Windows.Forms.DragEventArgs) Handles ListBox1.DragEnter If e.Data.GetDataPresent(DataFormats.FileDrop) Then e.Effect = DragDropEffects.All End If End Sub Private Sub ListBox1_DragDrop(ByVal sender As Object, ByVal e As _ System.Windows.Forms.DragEventArgs) Handles ListBox1.DragDrop If e.Data.GetDataPresent(DataFormats.FileDrop) Then Dim MyFiles() As String Dim i As Integer ' Assign the files to an array. MyFiles = e.Data.GetData(DataFormats.FileDrop) ' Loop through the array and add the files to the list. For i = 0 To MyFiles.Length - 1 ListBox1.Items.Add(MyFiles(i)) Next End If End Sub
You may notice that in the DragEnter event the Effect is set to DragDropEffects.All. Because the files themselves are not actually being moved or copied, it does not really matter which AllowedEffects were set by the source, so specifying All means that dropping is enabled for any FileDrop.
In the above example the FileDrop format contains the full path for each file being dropped. Rather than populating a list, you could just as easily perform other operations on the files — for example, opening them in MDI (multiple-document interface) document windows.