2011-11-28 28 views
7

是否有可能从我的C#应用​​程序中获取当前在Windows资源管理器中选择的文件的列表?从C#应用程序获取WindowsExplorer中的当前选择?

我已经做了很多关于从C#等托管语言与Windows资源管理器进行交互的不同方法的研究。最初,我正在研究外壳扩展的实现(例如,herehere),但显然这是来自托管代码的一个坏主意,并且可能无论如何对我的情况可能是矫枉过正的。

接下来,我看着的PInvoke/COM解决方案,并发现this article,这使我这个代码:

 SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows(); 

     string filename; 
     ArrayList windows = new ArrayList(); 

     foreach(SHDocVw.InternetExplorer ie in shellWindows) 
     { 
      filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower(); 
      if(filename.Equals("explorer")) 
      { 
       Console.WriteLine("Hard Drive: {0}", ie.LocationURL); 
       windows.Add(ie); 

       var shell = new Shell32.Shell(); 
       foreach (SHDocVw.InternetExplorerMedium sw in shell.Windows()) 
       { 
        Console.WriteLine(sw.LocationURL); 
       } 

      } 
     } 

...但个别InternetExplorer对象有没有方法来获得当前的文件选择,尽管它们可以用来获取有关窗口的信息。

然后我发现this article正是我所需要的,但在C++中。以此为出发点,我尝试在我的项目中添加shell32.dll作为参考。我结束了以下内容:

 SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows(); 

     string filename; 
     ArrayList windows = new ArrayList(); 

     foreach(SHDocVw.InternetExplorer ie in shellWindows) 
     { 
      filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower(); 
      if(filename.Equals("explorer")) 
      { 
       Console.WriteLine("Hard Drive: {0}", ie.LocationURL); 
       windows.Add(ie); 
       var shell = (Shell32.IShellDispatch4)new Shell32.Shell(); 
       Shell32.Folder folder = shell.NameSpace(ie.LocationURL); 
       Shell32.FolderItems items = folder.Items(); 
       foreach (Shell32.FolderItem item in items) 
       { 
        ... 
       } 
      } 
     } 

这是稍微接近,因为我能够得到的窗口Folder对象,并为每个项目,但我还是不明白的方式来获得当前的选择。

我可能完全看错了位置,但我一直在追踪我唯一的线索。任何人都可以将我指向适当的PInvoke/COM解决方案吗?

回答

7

最后想出了一个解决方案,感谢这个问题:Get selected items of folder with WinAPI

我结束了以下,为了得到当前选择的文件列表:

IntPtr handle = GetForegroundWindow(); 

List<string> selected = new List<string>(); 
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); 
     } 
    } 
} 

显然window.Document对应的资源管理器窗口,这是不是很直观内的实际文件夹视图。但除了误导性的变量/方法名称之外,这完美地起作用。

相关问题