BrowseForFolder.cpp 1020 B

123456789101112131415161718192021222324252627282930313233
  1. #include "BrowseForFolder.h"
  2. #include <Windows.h>
  3. #include <ShlObj.h>
  4. #include <string>
  5. #include <Commdlg.h>
  6. using namespace std;
  7. int BrowseForFolder::SelectFile(string& path)
  8. {
  9. TCHAR szBuffer[MAX_PATH] = { 0 }; //存放选择文件的路径
  10. BROWSEINFO bi;
  11. ZeroMemory(&bi, sizeof(BROWSEINFO));
  12. bi.hwndOwner = NULL;
  13. bi.pszDisplayName = szBuffer;
  14. bi.lpszTitle = _T("从下面选择文件或文件夹:"); //_T()是在头文件tchar.h下的一个宏定义。
  15. bi.ulFlags = BIF_BROWSEINCLUDEFILES;
  16. LPITEMIDLIST idl = SHBrowseForFolder(&bi); //开始选择文件或文件夹
  17. if (NULL == idl)
  18. {
  19. return 0;
  20. }
  21. SHGetPathFromIDList(idl, szBuffer); //获取完整路径,否则szBuffer只会存储当前选择的文件或文件夹名称
  22. path = TCHAR2STRING(szBuffer);
  23. return 0;
  24. }
  25. std::string BrowseForFolder::TCHAR2STRING(TCHAR* STR)
  26. {
  27. int iLen = WideCharToMultiByte(CP_ACP, 0, STR, -1, NULL, 0, NULL, NULL);
  28. char* chRtn = new char[iLen * sizeof(char)];
  29. WideCharToMultiByte(CP_ACP, 0, STR, -1, chRtn, iLen, NULL, NULL);
  30. std::string str(chRtn);
  31. delete chRtn;
  32. return str;
  33. }