HomeC&C++WainTutorialsSamplesTip & TrickTools


The standard dialog box for selecting a folder is called SHBrowseForFolder. Today I will show a simple wrapper function for it.
First the function header:
std::string GetFolder(HWND aHwndOwner, const std::string aTitle)
{
The function takes two arguments; a HWND for the owner window and a string to be displayed on the dialog box. The function returns the path selected as a std::string, a empty string if the user select Cancel on the dialog box.
We ned an char array, which will be filled with the path name, and a structure:
   char temp[MAX_PATH];
   BROWSEINFO BrowseInfo;
Then we fill out the BrowseInfo structure:
   BrowseInfo.hwndOwner = aHwndOwner;
   BrowseInfo.pidlRoot = 0;
   BrowseInfo.pszDisplayName = temp;
   BrowseInfo.lpszTitle = aTitle.c_str();
   BrowseInfo.ulFlags = BIF_USENEWUI;
   BrowseInfo.lpfn = 0;
   BrowseInfo.lParam = 0;
   BrowseInfo.iImage = 0;
If you compiler complains about the BIF_USENEWUI flag, you have to set ulFlags to 0 and you will get the old style box, which is not resizeable.
Then we call the dialogbox function:
   ITEMIDLIST *ItemList = SHBrowseForFolder(&BrowseInfo);
SHBrowseForFolder will return a NULL pointer if the user hits cancel, so we check:
   if(ItemList)
   {
Then we translate the ItemList into a normal path:
      SHGetPathFromIDList(ItemList, temp);
Now we are done, we just have to free the ItemList. To do so we have to get the allocater used by the shell, and use it to free:
      LPMALLOC Malloc;
      SHGetMalloc(&Malloc);
      Malloc->Free(ItemList);
      Malloc->Release();
And we are ready to return:
      return std::string(temp);
   }
If the user hits cancel we will return an empty string:
   return std::string("");
}
To use our function:
int main()
{
   std::string Path = GetFolder(0, "Select install path");
   MessageBox(0, Path.c_str(), "You selected:", MB_OK);
   return 0;
}
Here we use 0 as parent HWND, as this is a console app which does not have a window.
You have to include shlobj.h to use the SHxxx functions.
The code at a glance.