A Journey 2 Eternity

Getting an ITEMIDLIST For a Path

Posted on: April 15, 2009

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().

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Pages

Categories

April 2009
M T W T F S S
« Dec   May »
 12345
6789101112
13141516171819
20212223242526
27282930  

Blog Stats

  • 26,968 hits
%d bloggers like this: