如何在资源管理器中选择文件

How to get files selected in Explorer

我必须编辑使用 vb.net 语言 visual studio 编写的加载项。我需要的是一种从活动 windows 资源管理器 window 获取所有当前选定文件的列表的方法,以便我可以将其传递给程序中的另一个函数。我在 visual studio 方面不是很有经验(我的大部分经验都是在 VBA 中使用 VB 6.0)所以我在花太多时间之前寻求一些建议走错了路。

我正在考虑使用 Windows Shell 对象。我发现了一些用 C++ 编写的示例,并且我花了一些时间阅读 MSDN,但在我投入大量时间之前,我想在这里接触更有经验的 VB.Net/VS 用户。我知道 .Net 有很多内置选项用于处理 system.io 命名空间下的 file/folder 对象,但我还没有找到任何可以让我查看当前选择的项目的东西探险家 window。

我只是想知道 .Net 中是否有一些原生的东西可以满足我的需要?
如果不是,使用 Windows Shell 对象是最好的方法吗?

这只是 的小修改。与其像 linked 答案那样处理焦点项目,不如从 ShellFolderView 中获取选定的项目。 System.IO 不会对你有多大好处,因为 File/Folder 相关 类 与文件系统有关 - 这些文件不知道 Explorer 是否选择了它们。

首先,添加对Microsoft Shell Controls and AutomationMicrosoft Internet Controls的引用(见上文link)。

Imports Shell32
Imports SHDocVw

Private Function GetExplorerSelectedFiles() As String()
    Dim ExplorerFiles As New List(Of String)

    Dim exShell As New Shell


    For Each window As ShellBrowserWindow In DirectCast(exShell.Windows, IShellWindows)
        ' check both for either interface to work
        '    add an Exit for to just work the first explorer window 
        If TryCast(window.Document, IShellFolderViewDual) IsNot Nothing Then
            For Each fi As FolderItem In DirectCast(window.Document, IShellFolderViewDual).SelectedItems
                ExplorerFiles.Add(fi.Path)
            Next

        ElseIf TryCast(window.Document, ShellFolderView) IsNot Nothing Then
            For Each fi As FolderItem In DirectCast(window.Document, ShellFolderView).SelectedItems
                ExplorerFiles.Add(fi.Path)
            Next

        End If
    Next

    Return ExplorerFiles.ToArray
End Function

用法(点击按钮):

Dim files = GetExplorerSelectedFiles()
lbFiles.Items.AddRange(files)


已修改为适用于 IShellFolderViewDualShellFolderView