【问题标题】:Drag & drop and get file path in VB.NET在 VB.NET 中拖放并获取文件路径
【发布时间】:2012-07-26 01:30:26
【问题描述】:

我希望能够将文件/可执行文件/快捷方式拖到 Windows 窗体应用程序中,并让应用程序确定拖放文件的原始路径,然后将其作为字符串返回。

例如将图像从桌面拖到应用程序和消息框中,沿着图像的本地路径向上移动。

这可能吗?有人能给我举个例子吗?

【问题讨论】:

    标签: vb.net winforms drag-and-drop


    【解决方案1】:

    这很容易。只需通过将AllowDrop 属性设置为True 来启用拖放并处理DragEnterDragDrop 事件。

    DragEnter 事件处理程序中,您可以使用DataFormats 类检查数据是否属于您想要的类型。

    DragDrop事件处理程序中,使用DragEventArgsData属性接收实际数据和GetData方法


    示例:

    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
    

    【讨论】:

    • 更干净一点:Dim files() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())
    【解决方案2】:

    这只是说明如果拖放不起作用,可能是因为您在管理员模式下运行 Visual Studio(我相信是 Windows 7 及更高版本)。

    这也与您的 Windows 安装当前设置的 UAC 级别有关。

    【讨论】:

    • 非常好的考虑(但它应该作为有效答案下的评论添加)
    猜你喜欢
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多