【发布时间】:2015-02-19 19:24:06
【问题描述】:
我想获取焦点所在窗口的路径。
例如:我打开了 3 个窗口
一种。 C:\Windows
湾。 C:\Windows\System32
C。 C:\Users\COMP-0\Documents
我正在处理 c (C:\Users\COMP-0\Documents)
所以我想在 C# 中以编程方式获取此路径 (C:\Users\COMP-0\Documents)。
【问题讨论】:
我想获取焦点所在窗口的路径。
例如:我打开了 3 个窗口
一种。 C:\Windows
湾。 C:\Windows\System32
C。 C:\Users\COMP-0\Documents
我正在处理 c (C:\Users\COMP-0\Documents)
所以我想在 C# 中以编程方式获取此路径 (C:\Users\COMP-0\Documents)。
【问题讨论】:
在this answer 上展开以获取文件夹中的选定文件,您可以使用类似的方法来获取当前文件夹以及路径。
这需要一些 COM 并且需要:
GetForegroundWindow 获取活动窗口
SHDocVw.ShellWindows查找InternetExplorer窗口的当前列表,IShellFolderViewDual2 COM 接口获取活动窗口内的文件夹路径。有几个注意事项需要注意:
GUID 指向注册表中该文件夹的 CLSID。可能可以将该值转换为路径。null
如果在特殊文件夹或桌面中,此代码将仅返回当前窗口标题 - 通常是特殊文件夹的名称 - 使用 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);
【讨论】: