1. 程式人生 > 實用技巧 >使用Shell關閉指定資料夾視窗

使用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
            }
        }
    }
}