拖放以获取文件路径

时间:2013-02-23 04:40:39

标签: .net vb.net winforms

这是一个我无法开展工作的例子。我按照指示操​​作,但当我尝试将文件拖放到表单时,它不会让我,并给我不可用的光标。

这很容易。只需将drap-and-drop属性设置为True即可启用AllowDrop并处理DragEnter和DragDrop事件。在DragEnter事件处理程序中,您可以使用DataFormats类检查数据是否是您想要的类型。在DragDrop事件处理程序中,使用DataEventArgs的Data属性来接收实际数据。

示例:

Private Sub Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
  Handles MyBase.Load

    Me.AllowDrop = True
End Sub

Private Sub Form1_DragDrop(sender As System.Object, _
                           e As System.Windows.Forms.DragEventArgs) _
  Handles Me.DragDrop

    Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
    For Each path In files
        MsgBox(path)
    Next
End Sub

Private Sub Form1_DragEnter(sender As System.Object, _
                            e As System.Windows.Forms.DragEventArgs) _
  Handles Me.DragEnter

    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        e.Effect = DragDropEffects.Copy
    End If
End Sub

1 个答案:

答案 0 :(得分:4)

Imports System.IO

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.AllowDrop = True
    End Sub
    Private Sub Form1_DragDrop(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
        Dim theFiles() As String = CType(e.Data.GetData("FileDrop", True), String())
        For Each theFile As String In theFiles
            MsgBox(theFile)
        Next
    End Sub

    Private Sub Form1_DragEnter(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Copy
        End If
    End Sub
End Class