How to get files selected in Explorer

2.9k views Asked by At

I have to edit an add-in that was written in visual studio in the vb.net language. What I need is a way to get a list of all the currently selected files from the active windows explorer window so that I can pass this to another function within the program. I'm not super experienced in visual studio (most of my experience has been in VBA which uses VB 6.0) so I'm looking for some advice before I spend too much time going down the wrong path.

I was thinking of using the Windows Shell object. I've found some examples written in C++ and I've spent some time reading through the MSDN, but before I invest a ton of time in this I wanted to reach out here to more experienced VB.Net/VS users. I know .Net has a lot of built in options for dealing with file/folder objects under the system.io namespace, but I haven't found anything yet that would allow me to see what are the currently selected items in an explorer window.

I'm just wondering if there is something native within .Net that would do what I need?
If not, is using the Windows Shell object the best way to go?

1

There are 1 answers

16
Ňɏssa Pøngjǣrdenlarp On BEST ANSWER

This is just a minor revision of this answer. Rather than work off the focused item as the linked answer does, get the selected items from the ShellFolderView. System.IO wont do you much good because the File/Folder related classes have to do with the file system - the files have no idea if Explorer has them selected.

First, add reference to Microsoft Shell Controls and Automation and Microsoft Internet Controls (see the above 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

Usage (in a button click):

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

enter image description hereenter image description here


Modified to work on either IShellFolderViewDual or ShellFolderView