您的位置:首页 > 其它

VC中选择文件和文件夹的对话框

2013-11-28 21:26 316 查看
实现选择文件和选择文件夹不同,选择 文件 比较简单,只需要用一个类即可,实现 文件夹比较复杂 

(一)实现选择文件 

CFileDialog dlg(FALSE, //TRUE为打开对话框,FALSE为另存为对话框
"abc", //默认扩展名
"请选择要打开的文件", //编辑框中初始化的文字
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ENABLESIZING | OFN_FILEMUSTEXIST | OFN_READONLY,//对话框样式
"文本文档 (*.txt)|*.txt|所有文件 (*.*)|*.*||",//文件筛选功能
NULL) ; //所有者窗口

if( IDOK == dlg.DoModal())
{
CString strFileName = dlg.GetPathName();
AfxMessageBox(strFileName);
}

CFileDialog dlg(TRUE, 
".doc", 
"", 
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ENABLESIZING | OFN_FILEMUSTEXIST | OFN_READONLY,
"EXCEL文档 (*.xls)|*.xls|所有文件 (*.*)|*.*||",
NULL) ; 

if( IDOK == dlg.DoModal())
{
strFileName = dlg.GetPathName();
AfxMessageBox(strFileName);
}
else 
{
return;
}

说明:

1、用CFileDialog 就可以实现选择文件的对话框

2、选择到文件完整路径可以用dlg.GetPathName()来获取

(二)选择文件夹

LPMALLOC pMalloc; //先定义一个LPMALLOC
的变量
  /* Gets the Shell's default allocator */
  if (::SHGetMalloc(&pMalloc) == NOERROR)
  {
      BROWSEINFO bi;
      char pszBuffer[MAX_PATH];
      LPITEMIDLIST pidl;
      // Get help on BROWSEINFO struct - it's got all the bit settings.
      bi.hwndOwner = GetSafeHwnd();
      bi.pidlRoot = NULL;
      bi.pszDisplayName = pszBuffer;
      bi.lpszTitle = _T("get the directory for input");
      bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
      bi.lpfn = NULL;
      bi.lParam = 0;
      // This next call issues the dialog box.
      if ((pidl = ::SHBrowseForFolder(&bi)) != NULL)
      {
          if (::SHGetPathFromIDList(pidl, pszBuffer))
          {
              // At this point pszBuffer contains the selected path */.
              //DoingSomethingUseful(pszBuffer);
this->SetDlgItemText (IDC_IN,pszBuffer);

          }
          // Free the PIDL allocated by SHBrowseForFolder.
          pMalloc->Free(pidl);
      }
      // Release the shell's allocator.
      pMalloc->Release();
    }

说明:

1、这个实现是先定义一个BROWSEINFO 类型变量,然后每个成员赋值

2、通过pszBuffer获取文件夹的完整路径

CFileStatus
filestatus;
LPMALLOC pMalloc;
BROWSEINFO bi;
char pszBuffer[MAX_PATH];
LPITEMIDLIST pidl;

if (SHGetMalloc(&pMalloc) == NOERROR)
{
bi.hwndOwner = GetSafeHwnd();
bi.pidlRoot = NULL;
bi.pszDisplayName = pszBuffer;
bi.lpszTitle = _T("get the directory for input");
bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
bi.lpfn = NULL;
bi.lParam = IDR_MAINFRAME;

if ((pidl = SHBrowseForFolder(&bi)) != NULL)
{
if (SHGetPathFromIDList(pidl, pszBuffer))
{
this->SetDlgItemText(1,pszBuffer);
}
fpobj.destdirectory = pszBuffer;

// AfxMessageBox("读到的文件夹是:"+fpobj.destdirectory);
//CString tempstr1;
//tempstr1 = "读取到的文件夹路径:";
//AfxMessageBox(tempstr1 + pszBuffer);
pMalloc->Free(pidl);
}
else
{
return ;
}

pMalloc->Release();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息