获取文件资源管理器使用其窗口句柄显示的路径

时间:2015-04-08 09:56:52

标签: vb.net path handle explorer

我已成功使用

获取当前文件资源管理器窗口的句柄
'Get handle to active window
Dim hWnd As IntPtr = GetForegroundWindow()

我没有成功找到包含上述窗口显示的路径的对象。该路径应该驻留在窗口的过程中,也可以通过

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

但是,只有在IDE(VS2013)中执行时,Proc.MainModule.Filename才会传递进程的路径。外面执行时会突然停止。任何人都可以向我解释我无法理解的内容吗?感谢。

1 个答案:

答案 0 :(得分:2)

您可能能够迭代子窗口并获取文件名文本,但这似乎很难。假设Explorer是ForeGroundWindow作为起点也似乎很脆弱。以下是使用Shell32

获取Path / FocusedFile名称的方法

首先,打开References窗口(Project Properties - > References)。从COM选项卡中,选择/选中 Microsoft Internet Controls Microsoft Shell控件和自动化。注意:在Windows 8.1中,最后一个现在名为 Microsoft Shell文件夹视图路由器

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

使用它:

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

输出:

  

C:\温度