Get path that file explorer is displaying using its window handle
Asked Answered
G

1

3

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.

Garris answered 8/4, 2015 at 9:56 Comment(0)
C
2

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

Chessy answered 8/4, 2015 at 11:56 Comment(4)
Compiler says "IShellWindows not defined." And "For each was" throws a message too.Garris
Ok never mind. It worked flawlessly. Just make sure to fix the typo "w As" and also import SHDocVw where the IShellWindows interface is defined.Garris
Yes, I must have let VS add the Imports SHDocVw statement and forgot to add it here, the wAs was a paste errorBloodmobile
Thanks! I translate it to C#Agamemnon

© 2022 - 2024 — McMap. All rights reserved.