拖曳在VB.NET中拖放并获取文件路径 [英] Drag & drop and get file path in VB.NET

查看:330
本文介绍了拖曳在VB.NET中拖放并获取文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to be able to drag a file/executable/shortcut into a Windows Forms application and have the application determine the original path of the dropped file then return it as a string.

例如将图像从桌面拖到应用程序中,然后在消息框中将图像拖到图像的本地路径。

E.g. drag an image from the desktop into the application and messagebox up the local path of the image.

有可能吗?

推荐答案

这很容易。只需通过设置 AllowDrop 属性设置为 True 并处理 DragEnter DragDrop 事件。

It's quite easy. Just enable drap-and-drop by setting the AllowDrop property to True and handle the DragEnter and DragDrop events.

DragEnter 事件处理程序中,您可以使用 DataFormats 类。

In the DragEnter event handler, you can check if the data is of the type you want using the DataFormats class.

DragDrop 事件处理程序中,使用 Data 属性/ dotnet / api / system.windows.forms.drageventargs rel = noreferrer> DragEventArgs 接收实际数据和 GetData 方法

In the DragDrop event handler, use the Data property of the DragEventArgs to receive the actual data and the GetData method

示例:

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

这篇关于拖曳在VB.NET中拖放并获取文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆