【代码备忘】MFC遍历文件夹、删除文件夹、CTreeCtrl使用方法

欢迎加入我们的QQ群,无论你是否工作,学生,只要有c / vc / c++ 编程经验,就来吧!158427611 


所贴代码皆有一些工程代码,会对应标出!

【遍历文件夹 & CtreeCtrl插入节点】

void CDirTraversal::FindDir(HTREEITEM pItem , const CString &dirPath )//HTREEITEM 为一个CtreeCtel节点,此处实现将文件夹映射到CtreeCtrl控件中去

{
	CFileFind tempFind;   
	BOOL bFound = tempFind.FindFile(dirPath + "\\*.*");


	HTREEITEM pItem2;
	if(pItem == NULL)
	{
		pItem2 = m_treeCtrl->InsertItem(dirPath,0,1,TVI_ROOT,TVI_LAST);//插入根节点
	}
	else
	{
		pItem2 = m_treeCtrl->InsertItem(dirPath.Right(dirPath.GetLength() - dirPath.ReverseFind('\\') - 1),0,1,pItem,TVI_LAST);//插入子节点
	}
	while(bFound)
	{   
		bFound=tempFind.FindNextFile(); 
		if(tempFind.IsDots())   
			continue; 

		tempFind.IsDirectory() ? 
			FindDir(pItem2,tempFind.GetFilePath()) : //找到的是文件夹
			FindFile(pItem2,tempFind.GetFileName()); //找到的是文件
	}   
	tempFind.Close();   
}

void CDirTraversal::FindFile( HTREEITEM pItem ,const CString &filePath )
{
	m_treeCtrl->InsertItem(filePath,0,1,pItem,TVI_LAST); //插入子节点
}

【删除文件夹】

BOOL COEMToolDlg::DeleteDirectory(const CString &DirName)
{
	CFileFind tempFind;
	BOOL IsFinded = tempFind.FindFile(DirName + "\\*.*");
	while(IsFinded)
	{
		IsFinded = tempFind.FindNextFile();

		if(tempFind.IsDots())
			continue;

		if(tempFind.IsDirectory())
		{
			DeleteDirectory(tempFind.GetFilePath());
		}
		else
		{
			DeleteFile(tempFind.GetFilePath());
		}		
	}
	tempFind.Close();
	if(!RemoveDirectory(DirName))
	{
		MessageBox(L"删除目录失败!",L"警告信息",MB_OK);
		return FALSE;
	}
	return TRUE;
}

【CtreeCtrl的右键响应 & 获取右键对应节点】

void COEMToolDlg::OnNMRClickTree_RCLICK(NMHDR *pNMHDR, LRESULT *pResult)
{ 
	CPoint point;
	GetCursorPos(&point);  //获取鼠标坐标
	m_dirTree_treeCtrl.ScreenToClient(&point);//映射到CtreeCtrl中
	UINT nFlags;
	HTREEITEM hItems= m_dirTree_treeCtrl.HitTest(point, &nFlags);//根据坐标获取节点
	m_treeChangeFile = m_dirTree_treeCtrl.GetItemText(hItems); 
	hItems = m_dirTree_treeCtrl.GetParentItem(hItems);
	while(hItems) //循环获取父节点,获取节点全路径
	{
		m_treeChangeFile = m_dirTree_treeCtrl.GetItemText(hItems) + L"\\" + m_treeChangeFile;

		hItems = m_dirTree_treeCtrl.GetParentItem(hItems);
	}

	// 菜单显示
	CMenu menu;
	menu.LoadMenu(IDR_MENU_TREE);
	CMenu *pPopup=menu.GetSubMenu(0);
	POINT	 pt;
	::GetCursorPos((LPPOINT)&pt);

	pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y,this);

	*pResult = 0;
}


欢迎加入我们的QQ群,无论你是否工作,学生,只要有c / vc / c++ 编程经验,就来吧!158427611 

你可能感兴趣的:(遍历,mfc,经验,控件,menu)