MFC BROWSEINFO使用获取路径并且记忆打开路径
MFC中我们往往需要遍历某个路径下的某个相关类型的文件,这就需要获取目录,我们一般使用的 BROWSEINFO 获取路径信息默认都是从根目录开始展开,而CFileDialog获取的一般都是文件路径,也想过用CFileDialog获取文件路径,再剔除文件来获取目录,但始终不是所想要的那种效果。
下面通过BROWSEINFO获取路径,并且通过创建一个文件来保存每次打开的目录从而达到记忆路径功能。
1.设置一个全局变量来保存路径,这个是为了保证程序执行后的路径记忆:
static TCHAR g_szLastSelDir[MAX_PATH];
2.设置一个flag,程序执行以后就不用再从文件中来读取路径了,从上面的全局变量中读取路径。
static bool START_FLAG
3.获取路径程序如下
char buf[255]; //用来保存得到的路径 //程序开始时直接从文件中读取 if(START_FLAG == false) { CString LastPath = LastPahtGet(); _tcscpy(g_szLastSelDir, LastPath); } //程序开始 设置flag START_FLAG = true; BROWSEINFO bi; LPITEMIDLIST lp; CString BufferStr = _T(""); CString ShowBuffer = _T(""); ShowBuffer.LoadString(IDS_PRC_INPUT); ZeroMemory(buf, sizeof(buf)); bi.hwndOwner = m_hWnd; bi.pidlRoot = NULL; bi.pszDisplayName = buf; bi.lpszTitle = ShowBuffer; bi.ulFlags = BIF_RETURNONLYFSDIRS; bi.lpfn = BrowseCallbackProc;//设置回调函数,实现记忆路径 bi.lParam = 0; bi.iImage = 0; lp = SHBrowseForFolder(&bi); PRC_IN_FLAG = false; if(lp!=NULL) { SHGetPathFromIDList(lp,buf); if(START_FLAG == true) { _tcscpy(g_szLastSelDir, buf);//程序执行后,获取路径 } PrcFileIntPath = CString(buf); LastPathSet(PrcFileIntPath);//每次打开目录,保存目录到文件 }
4.再把获取路径和写路径的程序也贴出来吧
获取写路径到文件中 void LastPathSet(CString LastPath) { CStdioFile m_ReadMe; CString LineGetString = _T(""); CString ReadMeInf[1000]; bool PathFlag = false; int i = 0; int j = 0; //ReadMePath自己定义一个文件路径 if( m_ReadMe.Open( ReadMePath, CFile::modeWrite|CFile:: modeCreate) ==0) { return; } else { m_ReadMe.WriteString(CString("LASTPATH:") + LastPath + CString("\\")); m_ReadMe.Close(); } }
从文件中获取路径 CString LastPahtGet(void) { CStdioFile m_ReadMe; int i; CString LineGetString = _T(""); if( m_ReadMe.Open( ReadMePath, CFile::modeRead|CFile::typeBinary) ==0) { return NULL; } else { m_ReadMe.ReadString(LineGetString); if(LineGetString.Find(CString("LASTPATH:"))!=-1) { LastPath = LineGetString.Mid(9,LineGetString.GetLength()-10); } m_ReadMe.Close(); if(PathFileExists(LastPath))//判断该路径是否存在 { return LastPath; } else { return CString(""); } } return CString(""); }
路径文件中的字段
LASTPATH:C:\Documents and Settings\cnkangjb\デスクトップ\prc\