vb.net 拖放以获取文件路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15037128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:29:01  来源:igfitidea点击:

Drag and drop to get path of file

.netvb.netwinforms

提问by Danny Boy

Here is an example that I cannot get to work. I followed the directions, but when I try to drag and drop a file to the form, it doesn't let me, and gives me the Unavailable cursor.

这是我无法开始工作的示例。我按照说明操作,但是当我尝试将文件拖放到表单中时,它不允许我,并给我不可用光标。

It's quite easy. Just enable drap-and-dropby setting the AllowDropproperty to True and handle the DragEnter and DragDrop events. In the DragEnterevent handler, you can check if the data is of the type you want using the DataFormats class. In the DragDropevent handler, use the Data property of the DataEventArgsto receive the actual data.

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

Example:

例子:

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

回答by coder

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