如何在C#中获取Windows资源管理器的选定文件?

我需要获取在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); } } } 

你不需要得到Handle(探险家)。

在项目的引用中添加COM部分中的这些引用。 需要引用SHDocVw,它是Microsoft Internet Controls COM对象和Shell32 ,它是Microsoft Shell控件和自动化COM对象。

然后添加你的:

 using System.Collections; using Shell32; using System.IO; 

然后这将工作:

  string filename; ArrayList selected = new ArrayList(); foreach (SHDocVw.InternetExplorer window in new SHDocVw.ShellWindowsClass()) { 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