使用Shell关闭指定文件夹窗口

使用Shell对象的COM API可以检索和识别文件资源管理器窗口,涉及到的COM引用为:Microsoft Shell Controls And Automation,Microsoft Internet Controls。引入后,他们分别引用了Interop.shell32.dll、Interop.SHDocVw.dll。

Shell.Windows方法返回Ienumerable对象,它里面的成员是SHDocVw.InternetExplorer类型实例,如果它的Document属性是Shell32.ShellFolderView类型,那么该对象就是文件管理器对象。根据Shell32.ShellFolderView对象的Folder属性,可以处理不同的文件管理器需求。

需要注意的是,如果要将软件分发到别的电脑,可能会报这样的错误:无法将类型为“Shell32.ShellClass”的 COM 对象强制转换为接口类型“Shell32.IShellDispatch 6”。这是因为通过VS COM引用引入的Interop.shell32.dll版本太低(1.0.0),需要重新下载高版本的库文件才能正常使用。

参考资料

/// <summary>
/// 关闭文件夹窗口
/// </summary>
/// <param name="windowName">文件夹窗口名称</param>
public static void CloseExplorerWindows(string windowName)
{
    if (string.IsNullOrEmpty(windowName))
    {
        return;
    }

    var shell = new Shell32.Shell();

    // ref: Shell.Windows method
    // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774107(v=vs.85).aspx
    var windows = shell.Windows() as System.Collections.IEnumerable;
    if (windows != null)
    {
        // ref: ShellWindows object
        // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773974(v=vs.85).aspx
        foreach (SHDocVw.InternetExplorer window in windows)
        {
            object doc = window.Document;
            var view = doc as Shell32.ShellFolderView;
            if (windowName.Equals(view?.Folder.Title))
            {
                window.Quit();  // closes the window
            }
        }
    }
}
posted @ 2020-09-16 10:53  xhubobo  阅读(670)  评论(0编辑  收藏  举报