如何从C#中获取Windows资源管理器的选定文件? [英] How to get Windows Explorer's selected files from within C#?

查看:93
本文介绍了如何从C#中获取Windows资源管理器的选定文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取Windows资源管理器中所选文件的当前集合.我从这里.

I need to get the current collection of files that are selected in Windows Explorer. I found the following code from here.

不过,我还没到那儿.一方面, GetForegroundWindow 来自哪里?还有一件事,编译器在网上抱怨

I'm not quite there, though. For one thing, where does GetForegroundWindow come from? And for another thing, the compiler complains on the line

var shell = new Shell32.Shell();

"找不到类型或名称空间名称"Shell32"(您是缺少using指令或程序集引用吗?)".我已经添加了SHDocVw作为参考,但是我仍然无法通过编译器.能有人请帮助我完成此操作?

"The type or namespace name 'Shell32' could not be found (are you missing a using directive or an assembly reference?)". I have added SHDocVw as a reference, but I still can't get past the compiler. Can someone please help me get this completed?

    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);
            }
        }
    }

推荐答案

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

you don't need to get the Handle (of explorer).

在项目的引用中添加在 COM 部分中找到的这些引用.需要引用SHDocVw,这是 Microsoft Internet Controls COM对象和 Shell32 ,这是Microsoft Shell Controls and Automation COM对象.

In the project's references add these references found in the COM section. One needs to a reference to SHDocVw, which is the Microsoft Internet Controls COM object and Shell32, which is the Microsoft Shell Controls and Automation COM object.

然后添加您的:

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);
          }
        }
      }

这篇关于如何从C#中获取Windows资源管理器的选定文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆