Visual Basic Concepts

Dragging Files From the Windows Explorer

See Also

You can use OLE drag-and-drop to drag files from the Windows Explorer into an appropriate Visual Basic control, or vice versa. For example, you can select a range of text files in the Windows Explorer and then open them all in a single text box control by dragging and dropping them onto the control.

To illustrate this, the following procedure uses a text box control and the OLEDragOver and OLEDragDrop events to open a range of text files using the Files property and the vbCFFiles data format of the DataObject object.

To drag text files into a text box control from the Windows Explorer

  1. Start a new project in Visual Basic.

  2. Add a text box control to the form. Set its OLEDropMode property to Manual. Set its MultiLine property to True and clear the Text property.

  3. Add a function to select and index a range of files. For example:
    Sub DropFile(ByVal txt As TextBox, ByVal strFN$)
        Dim iFile As Integer
        iFile = FreeFile
    
        Open strFN For Input Access Read Lock Read _ 
    Write As #iFile
        Dim Str$, strLine$
        While Not EOF(iFile) And Len(Str) <= 32000
            Line Input #iFile, strLine$
            If Str <> "" Then Str = Str & vbCrLf
            Str = Str & strLine
        Wend
        Close #iFile
    
        txt.SelStart = Len(txt)
        txt.SelLength = 0
        txt.SelText = Str
    
    End Sub
    
  4. Add the following procedure to the OLEDragOver event. The GetFormat method is used to test for a compatible data format (vbCFFiles).
    Private Sub Text1_OLEDragOver(Data As _ 
    VB.DataObject, Effect As Long, Button As Integer, _ 
    Shift As Integer, X As Single, Y As Single, State _ 
    As Integer)
        If Data.GetFormat(vbCFFiles) Then
            'If the data is in the proper format, _
    inform the source of the action to be taken
        Effect = vbDropEffectCopy And Effect
            Exit Sub
        End If
        'If the data is not desired format, no drop
        Effect = vbDropEffectNone
    
    End Sub
    
  5. Finally, add the following procedure to the OLEDragDrop event.
    Private Sub Text1_OLEDragDrop(Data As _ 
    VB.DataObject, Effect As Long, Button As Integer, _ 
    Shift As Integer, X As Single, Y As Single)
        If Data.GetFormat(vbCFFiles) Then
            Dim vFN
    
            For Each vFN In Data.Files
                DropFile Text1, vFN
            Next vFN
        End If
    End Sub
    
  6. Run the application, open the Windows Explorer, highlight several text files, and drag them into the text box control. Each of the text files will be opened in the text box.