SHBrowseForFolder 打开默认路径

转自:http://blog.csdn.net/shuilan0066/article/details/7302904

一般的路径方式如下:
 BROWSEINFO bi;
 ZeroMemory(&bi,sizeof(BROWSEINFO));
 LPMALLOC pMalloc;
 LPITEMIDLIST pidl = SHBrowseForFolder(&bi);

 if (pidl==NULL)
   return;

 if(pidl != NULL)
 {
  TCHAR * path = new TCHAR[MAX_PATH]; 
  
  SHGetPathFromIDList(pidl,path);
  //  MessageBox(NULL,path,TEXT("Choose"),MB_OK);
  if(SUCCEEDED(SHGetMalloc(&pMalloc)))//pidl指向的对象用完应该释放,之前忽略了
  {
   pMalloc->Free(pidl);
   pMalloc->Release();
  }
  m_filePath=path;
  UpdateData(FALSE); 

     delete [] path;
 }

这样打开的是根目录,每次都定位到根目录中, 很是麻烦

能不能打开指定的目录呢? 答案是肯定的

 

第1步: 建立类的CALLBACK函数
public:

 static int CALLBACK  BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lParam,LPARAM lpData)
 {
  switch(uMsg)
  {
  case BFFM_INITIALIZED:    //初始化消息
   ::SendMessage(hwnd,BFFM_SETSELECTION,TRUE,(LPARAM)(LPTSTR)(LPCTSTR)m_filePath);   //  m_filePath 为类的静态变量
   break;
  case BFFM_SELCHANGED:    //选择路径变化,
   {
    TCHAR curr[MAX_PATH];  
    SHGetPathFromIDList((LPCITEMIDLIST)lParam,curr);  
    ::SendMessage(hwnd,BFFM_SETSTATUSTEXT,0,(LPARAM)curr);  
   }
   break;
  default:
   break;
  }
  return 0;  
 }

第2步:指定BROWSEINFO bi的相关信息

 BROWSEINFO bi;
 ZeroMemory(&bi,sizeof(BROWSEINFO));

 TCHAR szDefaultDir[MAX_PATH];
 CString strDef(_T("C:\\WINDOWS\\"));
 memcpy(szDefaultDir,strDef.GetBuffer(strDef.GetLength()*2),strDef.GetLength()*2);
 strDef.ReleaseBuffer();
 szDefaultDir[strDef.GetLength()]=0;

 bi.hwndOwner = this->GetSafeHwnd();
 bi.pidlRoot = 0;
 bi.pszDisplayName = 0;
 bi.lpszTitle = L"选择路径";
 bi.ulFlags = BIF_STATUSTEXT;
 bi.lpfn = BrowseCallbackProc ;        //设置CALLBACK函数
 bi.iImage = 0;
 bi.lParam = long(&szDefaultDir);    //设置默认路径

 LPMALLOC pMalloc;
 LPITEMIDLIST pidl = SHBrowseForFolder(&bi);

 if (pidl==NULL)
   return;

 if(pidl != NULL)
 {
  TCHAR * path = new TCHAR[MAX_PATH]; 
  
  SHGetPathFromIDList(pidl,path);
  if(SUCCEEDED(SHGetMalloc(&pMalloc)))//pidl指向的对象用完应该释放
  {
   pMalloc->Free(pidl);
   pMalloc->Release();
  }
  m_filePath=path;

  // 将路径保存在文件中
  CString pathSet;
  pathSet=m_exePath+L"UnionPicSet.ini";
  WritePrivateProfileString(_T("Path"),_T("DirectoryPath"),m_filePath,pathSet);

  UpdateData(FALSE); 
     delete [] path;

 }

翻译自:

http://blog.csdn.net/reallyioio/article/details/2948755




你可能感兴趣的:(SHBrowseForFolder 打开默认路径)