从c#应用程序中获取WindowsExplorer中的当前选择

本文关键字:选择 获取 应用程序 WindowsExplorer | 更新日期: 2023-09-27 18:15:50

是否可以从我的c#应用程序中获得当前在Windows资源管理器中选择的文件列表?

我已经做了很多关于使用c#等托管语言与Windows资源管理器交互的不同方法的研究。最初,我正在研究shell扩展的实现(例如这里和这里),但显然,在托管代码中这是一个坏主意,并且对于我的情况可能是多余的。

接下来,我查看了PInvoke/COM解决方案,找到了这篇文章,它引导我找到了这段代码:

        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对象没有方法来获取当前的文件选择,尽管它们可以用来获取有关窗口的信息。

然后我发现这篇文章做的正是我需要的,但是用的是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解决方案?

从c#应用程序中获取WindowsExplorer中的当前选择

终于找到了解决方案,感谢这个问题:使用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对应于资源管理器窗口内的实际文件夹视图,这不是很直观。但是,除了容易引起误解的变量/方法名之外,这个方法工作得很好。