#include "StdAfx.h"
#include "explorer_util.h"
#include <shlobj.h>
#include <Shlwapi.h>
// 打开已经存在的同步盘文件夹;
bool gAppFindExistSyncFolder(const QString& syncDir, HWND& hwndSync)
{
bool success = false;
IShellWindows *pShellWindows = NULL;
IDispatch *pDispatch = NULL;
IWebBrowserApp *pWebBrowserApp = NULL;
IServiceProvider *pServiceProvider = NULL;
IShellBrowser *pShellBrowser = NULL;
IShellView *pShellView = NULL;
IFolderView *pFolderView = NULL;
IPersistFolder2 *pPersistFolder2 = NULL;
LPITEMIDLIST pCurFolderIDLIST = NULL;
IShellFolder *pShellFolder = NULL;
IEnumIDList *pSelectionIDList = NULL;
TCHAR szPath[MAX_PATH];
szPath[0] = TEXT('\0');
//CoInitialize(NULL);
CO_TRY(CoCreateInstance(CLSID_ShellWindows, NULL, CLSCTX_ALL,
IID_IShellWindows, (void**)&pShellWindows));
{
HRESULT hr;
long count = 0;
CO_TRY(pShellWindows->get_Count(&count));
VARIANT v;
V_VT(&v) = VT_I4;
V_I4(&v) = 0;
for (int i = 0; i < count; i++, V_I4(&v)++)
{
hr = pShellWindows->Item(v, &pDispatch); // 当同步盘路径打开时,这里可能导致不返回导致卡死,目前原因不明,待查;
if (hr != S_OK)
goto __continue;
hr = pDispatch->QueryInterface(IID_IWebBrowserApp, (void**)&pWebBrowserApp);
if (hr != S_OK)
goto __continue;
HWND hwndWBA = NULL;
hr = pWebBrowserApp->get_HWND((LONG_PTR*)&hwndWBA);
if (hr != S_OK)
goto __continue;
hr = pWebBrowserApp->QueryInterface(IID_IServiceProvider, (void**)&pServiceProvider);
if (hr != S_OK)
goto __continue;
hr = pServiceProvider->QueryService(SID_STopLevelBrowser, IID_IShellBrowser, (void**)&pShellBrowser);
if (hr != S_OK)
goto __continue;
hr = pShellBrowser->QueryActiveShellView(&pShellView);
if (hr != S_OK)
goto __continue;
hr = pShellView->QueryInterface(IID_IFolderView, (void**)&pFolderView);
if (hr != S_OK)
goto __continue;
hr = pFolderView->GetFolder(IID_IPersistFolder2, (void**)&pPersistFolder2);
if (hr != S_OK)
goto __continue;
// 判断是否当前路径是否包含同步盘根目录;
hr = pPersistFolder2->GetCurFolder(&pCurFolderIDLIST);
if (hr != S_OK)
goto __continue;
// get current folder path
if (SHGetPathFromIDList(pCurFolderIDLIST, szPath)) {
QString folderPath = QString::fromWCharArray(szPath);
Q_DEBUG() << folderPath;
if (folderPath.contains(syncDir, Qt::CaseInsensitive))
{
hwndSync = hwndWBA;
break;
}
}
CO_FREE(pCurFolderIDLIST);
__continue:
CO_RELEASE(pSelectionIDList);
CO_RELEASE(pShellFolder);
CO_FREE(pCurFolderIDLIST);
CO_RELEASE(pPersistFolder2);
CO_RELEASE(pFolderView);
CO_RELEASE(pShellView);
CO_RELEASE(pShellBrowser);
CO_RELEASE(pServiceProvider);
CO_RELEASE(pWebBrowserApp);
CO_RELEASE(pDispatch);
}
}
success = true;
CO_CATCH
CO_RELEASE(pSelectionIDList);
CO_RELEASE(pShellFolder);
CO_FREE(pCurFolderIDLIST);
CO_RELEASE(pPersistFolder2);
CO_RELEASE(pFolderView);
CO_RELEASE(pShellView);
CO_RELEASE(pShellBrowser);
CO_RELEASE(pServiceProvider);
CO_RELEASE(pWebBrowserApp);
CO_RELEASE(pDispatch);
CO_RELEASE(pShellWindows);
//CoUninitialize();
return success;
}