Search code examples
vb.netpathhandleexplorer

Get path that file explorer is displaying using its window handle


I've succesfully obtained the handle to the current File Explorer window using

'Get handle to active window
Dim hWnd As IntPtr = GetForegroundWindow()

I have not been succesful finding the object that contains the path the aforementioned window is displaying. This path is supposed to reside in the process of the window, obtained too by

Dim ProcessID As UInt32 = Nothing
Dim ptr As UInt32 = GetWindowThreadProcessId(hWnd, ProcessID)
Dim Proc As Process = Process.GetProcessById(ProcessID)

However Proc.MainModule.Filename will deliver the path to the process only when executed within the IDE (VS2013). It will suddenly stop when executed outside. Can anyone please explain to me what I am failing to understand? Thanks.


Solution

  • You might be able to iterate child windows and get the filename text, but that seems to be the hard way. Assuming that Explorer is the ForeGroundWindow as a starting point also seems brittle. Here is how to get the Path/FocusedFile name using Shell32

    First, open the References window (Project Properties -> References). From the COM tab, select/check Microsoft Internet Controls and Microsoft Shell Controls and Automation. Note: in Windows 8.1, the last one is now named Microsoft Shell Folder View Router

    Imports Shell32               ' for ShellFolderView
    Imports SHDocVw               ' for IShellWindows
     ...
    
    Private Function GetExplorerPath() As String
        Dim exShell As New Shell
        Dim SFV As ShellFolderView
    
        For Each w As ShellBrowserWindow In DirectCast(exShell.Windows, IShellWindows)
            ' try to cast to an explorer folder
            If TryCast(w.Document, IShellFolderViewDual) IsNot Nothing Then
                expPath = DirectCast(w.Document, IShellFolderViewDual).FocusedItem.Path
                    ' remove the GetDirectoryName method when you
                     ' want to return the selected file rather than folder
                 Return Path.GetDirectoryName(expPath)
            ElseIf TryCast(w.Document, ShellFolderView) IsNot Nothing Then
                expPath = DirectCast(w.Document, ShellFolderView).FocusedItem.Path
                Return Path.GetDirectoryName(expPath)
    
            End If
        Next
    
        Return ""
    End Function
    

    To use it:

    Dim ExpPath = GetExplorerPath()
    Console.WriteLine(ExpPath )
    

    Output:

    C:\Temp