使用窗口句柄获取文件资源管理器正在显示的路径 [英] Get path that file explorer is displaying using its window handle

查看:151
本文介绍了使用窗口句柄获取文件资源管理器正在显示的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用

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

但是Proc.MainModule.Filename仅在IDE(VS2013)中执行时才将路径传递给进程.在外面执行时,它会突然停止.谁能给我解释一下我听不懂的内容吗?谢谢.

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.

推荐答案

您也许可以迭代子窗口并获取文件名文本,但这似乎很困难.假设Explorer是ForeGroundWindow的起点,那么它似乎也很脆弱.这是使用Shell32

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

首先,打开引用"窗口(项目属性"->引用").在"COM"选项卡中,选择/选中 Microsoft Internet控件 Microsoft Shell控件和自动化.注意:在Windows 8.1中,最后一个名称现在为 Microsoft Shell Folder View Router

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

要使用它:

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

输出:

C:\ Temp

C:\Temp

这篇关于使用窗口句柄获取文件资源管理器正在显示的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆