使用WindowsShell获取文件缩略图

HRESULT KThumbnailGetter::GetShellThumbnailImage(LPCWSTR pszPath, HBITMAP* pThumbnail)
{
    HRESULT hr;
    *pThumbnail = NULL;

    LPITEMIDLIST pidlItems = NULL, pidlURL = NULL, pidlWorkDir;
    WCHAR szBasePath[MAX_PATH], szFileName[MAX_PATH];
    WCHAR* p;
    wcscpy(szBasePath, pszPath);
    p = wcsrchr(szBasePath, L'\\');
    if (p) *(p + 1) = L'\0';
    wcscpy(szFileName, pszPath + (p - szBasePath) + 1);

    do
    {
        CComPtr psfDesktop;
        hr = SHGetDesktopFolder(&psfDesktop);
        if (FAILED(hr)) break;

        CComPtr psfWorkDir;
        DWORD dwAttribs = SFGAO_COMPRESSED;
        ULONG cbEaten;
        hr = psfDesktop->ParseDisplayName(NULL, NULL, szBasePath, &cbEaten, &pidlWorkDir, NULL);
        if (FAILED(hr)) break;
        hr = psfDesktop->BindToObject(pidlWorkDir, NULL, IID_IShellFolder, (LPVOID*)&psfWorkDir);
        if (FAILED(hr)) break;

        // 获取文件的PIDL
        hr = psfWorkDir->ParseDisplayName(NULL, NULL, szFileName, NULL, &pidlURL, NULL);
        if (FAILED(hr)) break;

        // 查询缩略图  
        CComPtr peiURL;
        hr = psfWorkDir->GetUIObjectOf(NULL, 1, (LPCITEMIDLIST*)&pidlURL, IID_IExtractImage, NULL, (LPVOID*)&peiURL);
        if (FAILED(hr)) break;

        // 定义缩略图属性
        SIZE size = { 256, 256 };
        DWORD dwPriority = 0, dwFlags = IEIFLAG_ASPECT;
        WCHAR pszImagePath[MAX_PATH];
        hr = peiURL->GetLocation(pszImagePath, MAX_PATH, &dwPriority, &size, 16, &dwFlags);
        if (FAILED(hr)) break;

        // 提取缩略图  
        hr = peiURL->Extract(pThumbnail);
        if (FAILED(hr)) break;

        break;
    } while (0);

    // 释放资源 
    if (pidlWorkDir) CoTaskMemFree(pidlWorkDir);
    if (pidlURL) CoTaskMemFree(pidlURL);
    return hr;
}

你可能感兴趣的:(C++,Windows)