Wednesday, April 15, 2009

Getting an ITEMIDLIST For a Path

If you have ever used ShBrowseForFolder(), you've probably noticed the pidlRoot member of the BROWSEINFO structure. It can be used to set the "root" folder to browse from. It's usually set to NULL, which means the "Desktop" folder.

Ever wanted to use another folder as the root for the "Browse For Folder" common dialog, but didn't know how to create an ITEMIDLIST for a given path? Here's a function that does it.

BOOL GetItemIdListFromPath (LPWSTR lpszPath, LPITEMIDLIST *lpItemIdList)

{

LPSHELLFOLDER pShellFolder = NULL;

HRESULT hr;

ULONG chUsed;

// Get desktop IShellFolder interface

if (SHGetDesktopFolder (&pShellFolder) != NOERROR)

return FALSE; // failed

// convert the path to an ITEMIDLIST

hr = pShellFolder->ParseDisplayName (

NULL, // owner window

NULL, // reserved (must be NULL)

lpszPath, // folder name

&chUsed, // number of chars parsed

lpItemIdList, // ITEMIDLIST

NULL // attributes (can be NULL)

);

if (FAILED(hr))

{

pShellFolder->Release();

*lpItemIdList = NULL;

return FALSE;

}

pShellFolder->Release();

return TRUE;

} // GetItemIdListFromPath

It's written in C++, but converting it to plain C is just a matter of changing a couple of lines. To do it, change all interface calls like: pShellFolder->ParseDisplayName() to pShellFolder->lpVtbl->ParseDisplayName(pShellFolder, ...), and similar changes to other calls.

Two things: The function receives the path as a UNICODE (LPWSTR) string, so you'll have to convert ANSI strings to unicode using MultiByteToWideChar() before calling the function. Finally, remember that you should free the memory referenced by the pointer to the ITEMIDLIST you get from the function by calling the Free() method of the IMalloc interface, which you can get using SHGetMalloc().

1 comment:

Unknown said...

Shouldn't you be attributing credit to:

http://winterdom.com/dev/ui/ishfolder