我想获得具有焦点的窗口的路径。
例如:我打开
了3 个窗口。C:\Windows
B. C:\Windows\System32
C. C:\用户\COMP-0\文档
我正在处理 c (C:\Users\COMP-0\Documents)
所以我想在 C# 中以编程方式获取此路径 (C:\Users\COMP-0\Documents)。
扩展此答案以获取文件夹中的选定文件,您可以使用类似的方法来获取当前文件夹及其路径。
这需要一些 COM 并且需要:
GetForegroundWindowInternetExplorer使用SHDocVw.ShellWindows,查找当前的窗口列表IShellFolderViewDual2COM 接口获取活动窗口内的文件夹路径。有几个注意事项需要注意:
GUID指向注册表中该文件夹的 CLSID。可能可以将该值转换为路径。null当前文件夹如果在特殊文件夹或桌面中,此代码将仅返回当前窗口标题 - 通常是特殊文件夹的名称 - 使用此答案中的详细信息。
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)