gpt4 book ai didi

C#获取焦点所在的Windows资源管理器路径

转载 作者:行者123 更新时间:2023-11-30 20:45:54 26 4
gpt4 key购买 nike

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

例如:我打开了 3 个窗口
A。 C:\Windows
b. C:\Windows\System32
C。 C:\Users\COMP-0\Documents

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

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

最佳答案

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

这需要一些 COM 并要求:

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

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

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

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

关于C#获取焦点所在的Windows资源管理器路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27590086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com