Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

FolderBrowser

5.00/5 (2 votes)
7 May 2012CPOL1 min read 18.1K   402  
Microsoft don't have a nice interface that used to select a specify folder.

Microsoft don't have a nice interface that used to select a specify folder. First, I search some code on the internet, but they don't work perfectly. So, I changed these code, and they become my FolderBrowser.

The class CFolderBrowser only has a static method, called SelectFolder. So you can call it without creating an object of FolderBrowser. In fact, we can just use a c style function to implent it. The core code of SelectFolder, call windows's Shell API.

  • SHGetSpecialFolderLocation(): It can get the Desktop's path.
  • SHBrowseForFolder(): It can show the window to select folder.
  • SHGetPathFromIDList(): It can get the selected folder as a string.

SHBrowseForFolder need the struct BROWSEINFO 's pointer as its parameter. All the input info can be found in BROWSEINFO. The lpfn member can accept a callback function. When the user open the selecting window or select any folder, lpfn will be called. So, we can use the callback function to set the initial path, and change the title when user select any folder.

The API SetCurrentDirectory(), can save the current folder. So, when you select folder next time, GetCurrentDirectory() can get the saved folder. You can use the current folder as the initial path, or not, as you like.

At last, the example code:

C++
CString strPath;
::GetCurrentDirectory(MAX_PATH, strPath.GetBuffer(MAX_PATH));
strPath.ReleaseBuffer();
if (CFolderBrowser::SelectFolder(this->m_hWnd, strPath))
 m_edit.SetWindowText(strPath);        // m_edit is an object of CEdit

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)