Programmatically select multiple files in windows explorer

前端 未结 8 1983
粉色の甜心
粉色の甜心 2020-11-28 11:01

I can display and select a single file in windows explorer like this:

explorer.exe /select, "c:\\path\\to\\file.txt"

However, I can

相关标签:
8条回答
  • 2020-11-28 11:55

    This is one of those questions where it may be good to consider what you're trying to achieve, and whether there's a better method.

    To add some more context - Our company develops a C# client application, which allows users to load files and do stuff with them, kind of like how iTunes manages your MP3 files without showing you the actual file on disk.

    It's useful to select a file in the application, and do a 'Show me this file in Windows Explorer` command - this is what I'm trying to achieve, and have done so for single files.

    We have a ListView which allows users to select multiple files within the application, and move/delete/etc them. It would be nice to have this 'show me this file in windows' command work for multiple selected files - at least if all the source files are in the same directory, but if it's not possible then it's not a major feature.

    0 讨论(0)
  • 2020-11-28 11:59

    There are COM Automation LateBinding IDispatch interfaces, these are easy to use from PowerShell, Visual Basic.NET and C#, some sample code:

    $shell = New-Object -ComObject Shell.Application
    
    function SelectFiles($filesToSelect)
    {
        foreach ($fileToSelect in $filesToSelect)
        {
            foreach ($window in $shell.Windows())
            {
                foreach ($folderItem in $window.Document.Folder.Items())
                {
                    if ($folderItem.Path -eq $fileToSelect)
                    {
                        $window.Document.SelectItem($folderItem, 1 + 8)
                    }
                }
            }
        }
    }
    

    -

    Option Strict Off
    
    Imports Microsoft.VisualBasic
    
    Public Class ExplorerHelp
        Shared ShellApp As Object = CreateObject("Shell.Application")
    
        Shared Sub SelectFile(filepath As String)
            For Each i In ShellApp.Windows
                For Each i2 In i.Document.Folder.Items()
                    If i2.Path = filepath Then
                        i.Document.SelectItem(i2, 1 + 8)
                        Exit Sub
                    End If
                Next
            Next
        End Sub
    End Class
    

    https://docs.microsoft.com/en-us/windows/win32/shell/shellfolderview-selectitem

    0 讨论(0)
提交回复
热议问题