目的:根据目录内容,建立一个菜单。菜单项为目录中的文件和子目录(以弹出方式显示)。
解决方案:遍历子目录,建立一个文件路径数组。菜单项的ID是数组的索引。当用户单击某个菜单项时,从数组中读取文件路径并执行相应的操作。
细节:
首先,我们需要一个菜单。新建立的菜单将作为此菜单的子菜单。
CMenu* pmenuFavorites=new CMenu;
pmenuFavorites->CreatePopupMenu();
然后读取目录,建立菜单
BuildFavoritesMenu(szPath, 0, pmenuFavorites);
最后,将菜单连接到已有菜单上面去
CMenu* pMenu=m_menuPopup.GetSubMenu(0);
pMenu->ModifyMenu(m_iMenuPosition,MF_BYPOSITION|MF_POPUP| MF_STRING,(UINT)(pmenuFavorites->GetSafeHmenu()),_T("动态菜单"));
pmenuFavorites->Detach();
delete pmenuFavorites;
其它的都很简单,但是建立这个菜单很麻烦
申明一个变量来存文件路径
CStringArray m_astrFavoriteURLs;
int CWorkBenchDlg::BuildMenu(LPCTSTR pszPath, int nStartPos, CMenu* pMenu)
{
CString strPath(pszPath);//path to start from
CString strPath2;//path to start from,with trailing backslash
CString str;//menu item text
WIN32_FIND_DATA wfd;
HANDLE h;
int nPos;
int nEndPos;
int nNewEndPos;
int nLastDir;
TCHAR buf[INTERNET_MAX_PATH_LENGTH];
CStringArray astrFavorites;
CStringArray astrDirs;
CMenu* pSubMenu;
// make sure there''s a trailing backslash
if(strPath[strPath.GetLength() - 1] != _T(''\\''))
strPath += _T(''\\'');
strPath2 = strPath;
strPath += _T("*.*");
// now scan the directory, first for files and then for subdirectories
//make a array of full pathnames.
h = FindFirstFile(strPath, &wfd);
if(h != INVALID_HANDLE_VALUE)
{
nEndPos = nStartPos;
do