微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我已经对从C#等托管语言与Windows资源管理器交互的不同方法做了大量研究.最初,我正在研究shell扩展的实现(例如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解决方案?

解决方法

最后找到了一个解决方案,感谢这个问题: 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对应于资源管理器窗口中的实际文件夹视图,这不是很直观.但除了误导性的变量/方法名称之外,这非常有效.

原文地址:https://www.jb51.cc/csharp/100213.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐