簡體   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