在MFC多文档文件视图中点击树控件的文件打开并显示文件路径
时间: 2024-05-08 12:16:33 浏览: 18
可以通过以下步骤实现:
1. 在树控件的双击事件中获取选中的文件路径。
```cpp
void CMyTreeView::OnTvnSelchanged(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
HTREEITEM hItem = pNMTreeView->itemNew.hItem;
CString strFilePath = GetItemFilePath(hItem); // 获取选中的文件路径
// 打开文件并显示
OpenDocumentFile(strFilePath);
*pResult = 0;
}
```
其中,`GetItemFilePath` 是一个自定义函数,用于获取树控件中选中的节点对应的文件路径。
2. 在 `OpenDocumentFile` 函数中打开并显示文件。
```cpp
BOOL CMyApp::OpenDocumentFile(LPCTSTR lpszFileName)
{
CWinApp* pApp = AfxGetApp();
ASSERT(pApp != NULL);
CDocument* pDoc = NULL;
POSITION pos = pApp->GetFirstDocTemplatePosition();
while (pos != NULL)
{
CDocTemplate* pTemplate = pApp->GetNextDocTemplate(pos);
ASSERT(pTemplate != NULL);
pDoc = pTemplate->OpenDocumentFile(lpszFileName);
if (pDoc != NULL)
{
pTemplate->InitialUpdateFrame(pDoc, NULL);
return TRUE;
}
}
return FALSE;
}
```
在 `OpenDocumentFile` 函数中,先通过 `GetFirstDocTemplatePosition` 和 `GetNextDocTemplate` 遍历应用程序中所有的文档模板,然后调用 `OpenDocumentFile` 函数打开文件,并调用 `InitialUpdateFrame` 函数更新主窗口中的视图。