ProblemYou want a ListBox control to accept file paths dragged to it from Windows Explorer. SolutionSample code folder: Chapter 14\DragDropFiles Use the control's DragEnter and DragDrop events to watch for dropped file lists and process them when dropped. DiscussionCreate a new Windows Forms application, and add a ListBox control named ListBox1 to Form1. Set this control's AllowDrop property to TRue. Now add the following code to the form's source code: Private Sub ListBox1_DragEnter(ByVal sender As Object, _ ByVal e As System.Windows.Forms.DragEventArgs) _ Handles ListBox1.DragEnter ' ----- Allow the dropping of file lists. If (e.Data.GetDataPresent(DataFormats.FileDrop) = _ True) Then e.Effect = DragDropEffects.Copy End If End Sub Private Sub ListBox1_DragDrop(ByVal sender As Object, _ ByVal e As System.Windows.Forms.DragEventArgs) _ Handles ListBox1.DragDrop ' ----- Process each dropped file. For Each oneFile As String In _ e.Data.GetData(DataFormats.FileDrop) ListBox1.Items.Add(oneFile) Next oneFile End Sub To test the program, run it, and then drag one or more files from Windows Explorer (or any other program that supports the dragging of files). Figure 14-12 shows the result of a multifile drag operation. Accepting dragged files in a control is a two-step process:
In this recipe's code, the DragEnter event examines the data being dragged into the ListBox to determine if it will accept the content. In this case, it looks for a "file drop list" (identified by DataFormats.FileDrop). If it finds one, it tells the sender that it will accept the files through a Copy operation, setting the e.Effect property. By default, e.Effect is set to DragDropEffects.None, which indicates that the content is not acceptable. Figure 14-12. Three dragged files accepted by a ListBox controlIn the DragDrop event, the dragged content exposed through e.Data is accessed, and its "file drop list" content is extracted as a string array, which is then transferred to the ListBox control. If you are familiar with the clipboard operations exposed through the My.Computer.Clipboard object, you will recognize the use of the "file drop list" also available through the clipboard. See AlsoRecipe 14.15 shows you how to perform inter-ListBox drag-and-drop operations. |