MFC的介面中,需要實現這樣兩個功能:

1、在介面上加一個按鈕,單擊按鈕彈出一個對話方塊選擇檔案,在工程中獲得檔案的路徑;

2、在介面上加一個按鈕,單擊按鈕彈出一個對話方塊選擇資料夾,在工程中獲取資料夾的路徑。

一、獲取檔案路徑

 1 // -- 按鈕的訊息響應函式
2 void CDialogSampled::OnBnClickedButtonOpen()
3 {
4 // TODO: 在此新增控制元件通知處理程式程式碼
5 CString m_strFilePath = _T("");
6
7 //獲取檔案路徑名
8 LPCTSTR szFilter =_T("TXT(*.txt)|*.txt|LOG(*.log)|*.log|ALLSUPORTFILE(*.*)|*.*||");
9 CFileDialog dlgFileOpenImg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,szFilter,NULL);
10 //開啟txt檔案
11 if(dlgFileOpenImg.DoModal() == IDOK)
12 {
13 //讀取檔名
14 m_strFilePath = dlgFileOpenImg.GetPathName();
15 }
16 else
17 {
18 return;
19 }
20 }

二、獲取資料夾路徑

//選擇儲存路徑
void CDialogSampled::OnBnClickedButtonSavePathSelect()
{
// TODO: 在此新增控制元件通知處理程式程式碼
CString m_saveFilePath;
//開啟檔案,獲取檔案路徑名
TCHAR szPath[_MAX_PATH];
BROWSEINFO bi;
bi.hwndOwner = GetSafeHwnd();
bi.pidlRoot = NULL;
bi.lpszTitle = "Please select the input path";
bi.pszDisplayName = szPath;
bi.ulFlags = BIF_RETURNONLYFSDIRS;
bi.lpfn = NULL;
bi.lParam = NULL; LPITEMIDLIST pItemIDList = SHBrowseForFolder(&bi); if(pItemIDList)
{
if(SHGetPathFromIDList(pItemIDList,szPath))
{
m_saveFilePath = szPath;
m_saveFilePath = m_saveFilePath+"\\";
} //use IMalloc interface for avoiding memory leak
IMalloc* pMalloc;
if( SHGetMalloc(&pMalloc) != NOERROR )
{
TRACE(_T("Can't get the IMalloc interface\n"));
} pMalloc->Free(pItemIDList);
if(pMalloc)
pMalloc->Release();
UpdateData(FALSE);
}
}