C# 获取焦点所在的 Windows 探索路径

coo*_*uzz 3 c# winforms

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

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

我正在处理 c (C:\Users\COMP-0\Documents)

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

Rhu*_*orl 6

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

这需要一些 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:\Windows\system32\ShDocVw.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:\Windows\system32\Shell32.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);
Run Code Online (Sandbox Code Playgroud)