如何从c#中获取Windows资源管理器's选定的文件
本文关键字:文件 资源管理器 Windows 获取 | 更新日期: 2023-09-27 17:51:01
我需要获得在Windows资源管理器中选择的文件的当前集合。我从这里找到了下面的代码。
我还没完全明白。首先,GetForegroundWindow
从何而来?另外,编译器在
var shell = new Shell32.Shell();
说"类型或命名空间名称'Shell32'无法找到(您是否缺少using指令或程序集引用?)"。我添加了SHDocVw作为参考,但我仍然无法通过编译器。可以有人能帮我把这个完成吗?
IntPtr handle = GetForegroundWindow();
ArrayList selected = new ArrayList();
var shell = new Shell32.Shell();
foreach(SHDocVw.InternetExplorer window in shell.Windows()) {
if (window.HWND == (int)handle)
{
Shell32.FolderItems items = ((Shell32.IShellFolderViewDual2)window.Document).SelectedItems();
foreach(Shell32.FolderItem item in items)
{
selected.Add(item.Path);
}
}
}
你不需要获取(资源管理器的)句柄。
在项目的参考文献中添加COM
部分中的这些参考文献。需要引用SHDocVw,这是Microsoft Internet Controls
COM对象和Shell32
,这是Microsoft Shell Controls and Automation COM对象。
然后加上:
using System.Collections;
using Shell32;
using System.IO;
string filename;
ArrayList selected = new ArrayList();
foreach (SHDocVw.InternetExplorer window in new SHDocVw.ShellWindows())
{
filename = Path.GetFileNameWithoutExtension(window.FullName).ToLower();
if (filename.ToLowerInvariant() == "explorer")
{
Shell32.FolderItems items = ((Shell32.IShellFolderViewDual2)window.Document).SelectedItems();
foreach (Shell32.FolderItem item in items)
{
selected.Add(item.Path);
}
}
}
GetForegroundWindow是一个Win32 API函数,要使用它,你需要导入它,如下所示:getforegroundwindow (user32)
Shell32的描述如下:
在c#中使用shell 32
最后,我不知道你的任务,但通常如果有必要选择一些文件并访问这个集合,有必要使用FileOpenDialog