创建一个“选择文件夹”对话框
- 在InitInstance里面添加:
HRESULT CoInitializeEx(
void * pvReserved, //must be null currently
DWORD dwCoInit //see the following definition to COINIT
);
typedef enum tagCOINIT {
COINIT_MULTITHREADED = 0x0,
COINIT_APARTMENTTHREADED = 0x2,
COINIT_DISABLE_OLE1DDE = 0x4,
COINIT_SPEED_OVER_MEMORY = 0x8,
} COINIT;
2. cpp添加#define _WIN32_DCOM
3.函数实现:
BOOL CStyleView::GetFolderPath(CWnd *pWnd, CString &strPath)
{
TCHAR szTitle[] = _T("请选择对话框");
TCHAR szPath[MAX_PATH] = _T("");
BROWSEINFO bi;
if (!pWnd)
{
return FALSE;
}
memset(&bi, 0, sizeof(BROWSEINFO));
//设置父窗口句柄
bi.hwndOwner = pWnd->GetSafeHwnd();
//设置窗口标题
bi.lpszTitle = szTitle;
bi.ulFlags = BIF_USENEWUI;
LPITEMIDLIST pList = SHBrowseForFolder(&bi);
if (pList)
{
if (!SHGetPathFromIDList(pList, szPath))
{
return FALSE;
}
//防止内存泄露
IMalloc *pMalloc;
if (SHGetMalloc(&pMalloc) != NOERROR)
{
return FALSE;
}
pMalloc->Free(pList);
if (pMalloc)
{
pMalloc->Release();
}
}
//判断路径长度是否有效
if (_tcslen(szPath) <= 0)
{
return FALSE;
}
strPath.Format(_T("%s"), szPath);
return TRUE;
}