Wednesday, August 05, 2009

SHGetFolderLocation C++ sample code

Original code is from MSDN. Sample code demonstrates how to use  SHGetFolderLocation in C++.

#include 
#include 
#include 
#include 

int main()
{
    IShellFolder *psfParent = NULL;
    LPITEMIDLIST pidlSystem = NULL;
    LPCITEMIDLIST pidlRelative = NULL;
    STRRET strDispName;
    TCHAR szDisplayName[MAX_PATH];
    HRESULT hr;

    hr = SHGetFolderLocation(NULL, CSIDL_DESKTOP, NULL, NULL, &pidlSystem);
    if (!SUCCEEDED(hr))
    {
        std::cout << "hr bad" << std::endl;
        return -1;
    }

    hr = SHBindToParent(pidlSystem, IID_IShellFolder, (void **) &psfParent, &pidlRelative);

    if(SUCCEEDED(hr))
    {
        hr = psfParent->GetDisplayNameOf(pidlRelative, SHGDN_NORMAL, &strDispName);
        hr = StrRetToBuf(&strDispName, pidlSystem, szDisplayName, sizeof(szDisplayName));
        std::wcout << "SHGDN_NORMAL - " <<< '\n';
    }

    psfParent->Release();
    CoTaskMemFree(pidlSystem);

    return 0;
} 


Need to link ShlwApi.lib to get this to work (Project Properties | Configuration Properties | Linker | Input | Additional Dependencies)

~ts

No comments: