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

Bar*_*ert 9 c# windows-shell

我需要获取在Windows资源管理器中选择的当前文件集合.我从这里找到了以下代码.

不过,我不在那里.首先,它GetForegroundWindow来自哪里?另一方面,编译器在线上抱怨

var shell = new Shell32.Shell();
Run Code Online (Sandbox Code Playgroud)

"无法找到类型或命名空间名称'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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Dar*_*aro 7

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

在项目的参考资料中添加这些参考资料COM.需要引用SHDocVw,它是Microsoft Internet ControlsCOM对象Shell32,它是Microsoft Shell控件和自动化COM对象.

然后添加你的:

using System.Collections;
using Shell32;
using System.IO;
Run Code Online (Sandbox Code Playgroud)

然后这将工作:

      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);
          }
        }
      }
Run Code Online (Sandbox Code Playgroud)