DragDrop ideas
private void treeView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) { TreeNode NewNode; if(e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false)) { NewNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode"); if (!(sender as TreeView).Nodes.Contains(NewNode))//Edit: add this if you don't want to add the same one again. { (sender as TreeView).Nodes.Add((TreeNode) NewNode.Clone()); NewNode.Remove(); //Edit: add this if you want to remove original one. } } }
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
- Add a ListBox control to a form and set its AllowDrop property to True.
- 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 whichAllowedEffects 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.
What’s Changed from Visual Basic 6.0