2011-11-28 27 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對應的資源管理器窗口,這是不是很直觀內的實際文件夾視圖。但除了誤導性的變量/方法名稱之外,這完美地起作用。

相關問題