繁体   English   中英

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

[英]How to get Windows Explorer's selected files from within C#?

我需要获取在 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 控件和自动化 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM