2012-07-27 143 views
9

我想能够拖动一个文件/可执行文件/快捷方式到一个Windows窗体应用程序,并让应用程序确定所删除的文件的原始路径,然后将其作为字符串返回?VB.net - 拖放并获取文件路径?

E.g.将图像从桌面拖到应用程序中,然后将消息框拖到图像的本地路径上。

这可能吗?可能有人能为我提供一个例子吗?

谢谢

回答

30

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

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

DragDrop事件处理程序中,使用DataEventArgsData属性来接收实际数据。


例子:

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 
2

这仅仅是一个音符,从而指出,如果拖放不起作用,可能是因为您在管理员模式(Windows 7上运行Visual Studio和我相信)。这也与当前在Windows上设置的UAC级别有关。

+0

真的很好的考虑(但它应该添加为有效答案下的评论) – JCM 2017-02-24 09:59:22