vb.net 在VB.NET中拖放并获取文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11686631/
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
Drag & drop and get file path in VB.NET
提问by rabbitt
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.
我希望能够将文件/可执行文件/快捷方式拖动到 Windows 窗体应用程序中,并让应用程序确定所放置文件的原始路径,然后将其作为字符串返回。
E.g. drag an image from the desktop into the application and messagebox up the local path of the image.
例如,将图像从桌面拖动到应用程序和消息框,沿着图像的本地路径向上。
Is that possible? Could someone provide me with an example maybe?
那可能吗?有人可以为我提供一个例子吗?
回答by sloth
It's quite easy. Just enable drap-and-drop by setting the AllowDrop
property to True
and handle the DragEnter
and DragDrop
events.
这很容易。只需通过将AllowDrop
属性设置为True
和处理DragEnter
和DragDrop
事件来启用拖放。
In the DragEnter
event handler, you can check if the data is of the type you want using the DataFormats
class.
在DragEnter
事件处理程序中,您可以使用DataFormats
该类检查数据是否属于您想要的类型。
In the DragDrop
event handler, use the Data
property of the DragEventArgs
to receive the actual data and the GetData
method
在DragDrop
事件处理程序中,使用 的Data
属性DragEventArgs
来接收实际数据和GetData
方法
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 gouderadrian
This is just a note to state that if drag and drop does not work, it could be because you are running Visual Studio in Administrator Mode (Windows 7 and up I believe).
这只是说明如果拖放不起作用,可能是因为您在管理员模式下运行 Visual Studio(我相信 Windows 7 及更高版本)。
This also has to do with the UAClevel currently set on your Windows installation.
这也与当前在 Windows 安装上设置的UAC级别有关。