从 Windows“资源管理器”中拖动文件

可在 Windows“资源管理器”和合适的 Visual Basic 控件之间使用 OLE 拖放来拖动文件。例如,可在 Windows“资源管理器”中选定一组文本文件,然后将它们拖放到一个文本框控件中就可将文本全部打开。

为说明这一点,以下过程可用一个文本框控件以及 OLEDragOver 和 OLEDragDrop 事件,并用 DataObject 对象中的 Files 属性和 vbCFFiles 数据格式打开一组文本文件。

从 Windows 资源管理器中拖动文本文件到文本框控件

  1. 在 Visual Basic 中启动新的工程。

  2. 向窗体添加一个文本框控件并将其 OLEDropMode 属性设置为“手工”。将 MultiLine 属性设置为 True 并清除 Text 属性。

  3. 添加函数,选定一组文件。例如:
    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. 将以下过程添加到 OLEDragOver 事件中。用 GetFormat 方法检测兼容的数据格式 (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
    '若数据格式正确,_
    则将即将执行的操作通知源
    Effect = vbDropEffectCopy And Effect
    Exit Sub
    End If
    '若数据格式不合适,则不放下
    Effect = vbDropEffectNone
    
    End Sub
    
  5. 最后将下列过程添加到 OLEDragDrop 事件中。
    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. 运行应用程序,打开 Windows“资源管理器”,突出显示若干文本文件并将它们拖动到文本框控件中。在文本框中将打开每个文本文件。