16.讓對話方塊支援拖拽操作/目錄框開啟操作

zyddst1314發表於2020-11-30

1.開啟目錄對話方塊

void CMFCApplication7Dlg::OnBnClickedButton1()
{
	TCHAR szPath[MAX_PATH] = { 0 };
	BROWSEINFO mBroInfo = { 0 };
	mBroInfo.hwndOwner = m_hWnd;
	
	ITEMIDLIST *pidl = SHBrowseForFolder(&mBroInfo);//開啟檔案目錄對話方塊
	if (SHGetPathFromIDList(pidl, szPath));
	{
		SetDlgItemText(IDC_EDIT_PATH, szPath);
	}
	CoTaskMemFree(pidl);
	
	// TODO: 在此新增控制元件通知處理程式程式碼
}

2.目錄選擇對話方塊的根目錄設定

mBroInfo.pidlRoot = GetItemIdListFromPath(_T("D:\\"));


LPITEMIDLIST GetItemIdListFromPath(CString strPath)
{
	if (!strPath)
	{
		return NULL;
	}
	LPSHELLFOLDER pDesktopFolder = NULL;
	HRESULT hr = SHGetDesktopFolder(&pDesktopFolder);
	if (FAILED(hr))
	{
		return NULL;
	}
	PWCHAR pWchar = NULL;
#ifdef _UNICODE
	pWchar = (LPTSTR)(LPCTSTR)strPath;
#else
	USES_CONVERSION;
	pWchar = A2W(strPath);//轉換成寬位元組
#endif

	LPITEMIDLIST pItemIdList = NULL;
	hr = pDesktopFolder->ParseDisplayName(NULL, NULL, pWchar, NULL, &pItemIdList, NULL);
	pDesktopFolder->Release();
	if (FAILED(hr))
	{
		return NULL;
	}
	return pItemIdList;
}

3.拖拽功能

1.對話方塊模板的Accept Files屬性設定為True;
2.響應主對話方塊類的WM_DROPFILES訊息;
3.新增如下程式:

TCHAR szPath[MAX_PATH] = { 0 };
	UINT nCount = DragQueryFile(hDropInfo,0xFFFFFFFF,NULL,0);
	for (UINT idx = 0; idx < nCount; idx++)
	{
		DragQueryFile(hDropInfo, idx, szPath, MAX_PATH);
		MessageBox(szPath);
	}
	DragFinish(hDropInfo);

相關文章