【问题标题】:How to get Windows Explorer's selected files from within C#?如何从 C# 中获取 Windows 资源管理器的选定文件?
【发布时间】:2013-01-07 09:48:26
【问题描述】:

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

不过,我并不完全在那里。一方面,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);
            }
        }
    }

【问题讨论】:

标签: c# windows-shell


【解决方案1】:

您不需要获取(资源管理器的)句柄。

在项目的引用中添加这些在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);
          }
        }
      }

【讨论】:

  • 这看起来更好,除了我有另一个编译问题:
  • 编译问题是:无法嵌入互操作类型“SHDocVw.ShellWindowsClass”。请改用适用的接口。
  • 我将 ShellWindowsClass 更改为只是 ShellWindows,它似乎正在工作。谢谢大家!
  • 我已编辑答案以解决“无法嵌入”问题。回答 stackoverflow.com/a/4174056/1172352 解释了为什么 ShellWindows 比 ShellWindowsClass 更正确。
【解决方案2】:

GetForegroundWindow 是一个 Win32 API 函数,要使用它,您需要按照此处的说明导入它: getforegroundwindow (user32)

这里描述了Shell32:

working with shell 32 in C#

最后,我不知道你的任务,但通常如果需要选择一些文件并访问此集合,则需要使用FileOpenDialog

【讨论】:

  • 感谢您的帮助,我编译了程序,但它似乎不起作用。事实上,我想知道怎么可能?当我得到前景窗口时,这不会返回我的程序运行所在窗口的句柄,而不是 Windows 资源管理器包含我的选定文件列表的窗口吗?
  • GetForegroundWindow 方法检索前台窗口(用户当前正在使用的窗口)的句柄。所以,我不知道您的应用程序应该如何工作。如需枚举所有窗口,请参考codeproject.com/Articles/2286/Window-Hiding-with-C项目。
猜你喜欢
  • 2011-11-05
  • 2014-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 2013-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多