C# 获取具有焦点的 Windows 探索路径



我想获取具有焦点的窗口路径。

例如:我打开
了 3 个窗口a. C:\Windows
b. C:\Windows\System32
c. C:\用户\COMP-0\文档

我正在研究c(C:\Users\COMP-0\Documents(

所以我想在 C# 中以编程方式获取此路径(C:\Users\COMP-0\Documents(。

展开此答案以获取文件夹中的选定文件,您可以使用类似的方法来获取当前文件夹,从而获取其路径。

这需要一些 COM 并需要:

  • 使用 GetForegroundWindow获取活动窗口
  • 使用 SHDocVw.ShellWindows 查找InternetExplorer窗口的当前列表,
  • 匹配句柄指针以查找当前窗口
  • 使用 IShellFolderViewDual2 COM 接口获取活动窗口中的文件夹路径。

有几个注意事项需要注意:

  • 特殊文件夹(收藏夹、我的电脑等(将为您提供文件路径为"::{GUID}",其中GUID指向注册表中该文件夹的 CLSID。可以将该值转换为路径。
  • 转到"桌面"将返回当前文件夹的null
  • 聚焦 Internet Explorer 将在活动窗口中触发匹配,因此我们需要确保我们位于 Shell 文件夹中

如果在特殊文件夹或桌面中,此代码将仅使用此答案中的详细信息返回当前窗口标题 - 通常是特殊文件夹的名称。

private static string GetActiveExplorerPath()
{
    // get the active window
    IntPtr handle = GetForegroundWindow();
    // Required ref: SHDocVw (Microsoft Internet Controls COM Object) - C:Windowssystem32ShDocVw.dll
    ShellWindows shellWindows = new SHDocVw.ShellWindows();
    // loop through all windows
    foreach (InternetExplorer window in shellWindows)
    {
        // match active window
        if (window.HWND == (int)handle)
        {
            // Required ref: Shell32 - C:Windowssystem32Shell32.dll
            var shellWindow = window.Document as Shell32.IShellFolderViewDual2;
            // will be null if you are in Internet Explorer for example
            if (shellWindow != null)
            {
                // Item without an index returns the current object
                var currentFolder = shellWindow.Folder.Items().Item();
                // special folder - use window title
                // for some reason on "Desktop" gives null
                if (currentFolder == null || currentFolder.Path.StartsWith("::"))
                {
                    // Get window title instead
                    const int nChars = 256;
                    StringBuilder Buff = new StringBuilder(nChars);
                    if (GetWindowText(handle, Buff, nChars) > 0)
                    {
                        return Buff.ToString();
                    }
                }
                else
                {
                    return currentFolder.Path;
                }
            }
            break;
        }
    }
    return null;
}
// COM Imports
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

最新更新