【代码备忘】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 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值