【问题标题】:Get path that file explorer is displaying using its window handle使用其窗口句柄获取文件资源管理器正在显示的路径
【发布时间】:2015-06-13 05:20:23
【问题描述】:

我已经成功获得了当前文件资源管理器窗口的句柄

'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)

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

【问题讨论】:

    标签: vb.net path handle explorer


    【解决方案1】:

    您也许可以迭代子窗口并获取文件名文本,但这似乎是一种困难的方式。假设 Explorer 是以 ForeGroundWindow 为起点也似乎很脆弱。下面是如何使用Shell32获取路径/焦点文件名称

    首先,打开“参考”窗口(项目属性 -> 参考)。在 COM 选项卡中,选择/选中 Microsoft Internet ControlsMicrosoft Shell Controls and Automation。注意:在 Windows 8.1 中,最后一个现在命名为 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
    

    使用它:

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

    输出:

    C:\温度

    【讨论】:

    • 编译器说“IShellWindows 未定义”。而“For each was”也会抛出一条信息。
    • 好吧,没关系。它完美无缺。只需确保修复错字“w As”并在定义 IShellWindows 接口的位置导入 SHDocVw。
    • 是的,我一定是让VS添加了Imports SHDocVw语句而忘记在这里添加了,wAs是一个粘贴错误
    • 谢谢!我把它翻译成C#
    猜你喜欢
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 2011-01-31
    相关资源
    最近更新 更多