Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

saying

"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);
            }
        }
    }
like image 419
Barry Dysert Avatar asked Jan 07 '13 09:01

Barry Dysert


1 Answers

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

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.

Then add your:

using System.Collections;
using Shell32;
using System.IO;

Then this will work:

      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);
          }
        }
      }
like image 179
Daro Avatar answered Oct 22 '22 22:10

Daro