Page 1 of 1

Cum selectez un folder?

Posted: 17 Jul 2007, 15:30
by cristitm
Am folosit pana acum CFileDialog pentru a selecta un fisier. Acum imi trebuie sa selectez un folder. Nu-mi dau seama cum pot face clasa asta sa imi afiseze dialogul de selectare un folder. Se poate?

Re: Cum selectez un folder?

Posted: 17 Jul 2007, 18:56
by Marius Bancila
CFileDialog nu poate fi folosit decat pentru a selecta un fisier. Daca vrei sa selectezi un folder trebuie sa folosesti API-ul shell-ului de Windows numit SHBrowseForFolder.

Uite un exemplu:

Code: Select all

int CALLBACK BrowseCallbackProc(HWND hWnd, 
			UINT uMsg, 
			LPARAM lParam, 
			LPARAM pData )
{
	LPCTSTR pszRootDir = (LPCTSTR)pData;
	switch(uMsg)
	{
	case BFFM_INITIALIZED:
		{ 
			SendMessage(hWnd,BFFM_SETSELECTION,TRUE,(LPARAM)pszRootDir);
			break;
		}
	case BFFM_SELCHANGED:
		{
			LPTSTR pszSelDir = new TCHAR[_MAX_PATH];
			if( SHGetPathFromIDList((LPITEMIDLIST)lParam, pszSelDir)) 
			{
				SendMessage(hWnd,BFFM_SETSTATUSTEXT,0,(LPARAM)pszSelDir);
			}
			delete[] pszSelDir;
		}
	default:
		break;
	}
	return 0;
}

BOOL BrowseForFolder(HWND hWnd, LPCSTR lpszTitle, LPSTR& lpszDirectory)
{
	LPMALLOC lpMalloc;

	LPITEMIDLIST   pidl;
	HRESULT hr = SHGetSpecialFolderLocation(NULL, CSIDL_DRIVES, &pidl);
	if(FAILED(hr))
		return FALSE;

	if (::SHGetMalloc(&lpMalloc) != NOERROR)
		return FALSE;

	char szDisplayName[MAX_PATH] = {0};

	// set the parameters for the calls
	BROWSEINFO info;
	if(::IsWindow(hWnd))
		info.hwndOwner	= hWnd;
	else
		info.hwndOwner	= NULL;
	info.pidlRoot		= pidl;
	info.pszDisplayName = szDisplayName;
	info.lpszTitle		= lpszTitle;
	info.ulFlags		= BIF_DONTGOBELOWDOMAIN|BIF_STATUSTEXT;
	info.lpfn			= BrowseCallbackProc;
	info.lParam			= (LPARAM)lpszDirectory;
	info.iImage			= 0;

	LPITEMIDLIST lpItemIDList;

	// select the folder
	if ((lpItemIDList = SHBrowseForFolder(&info)) != NULL)
	{
		// use the return information to obtain the full folder path
		if (SHGetPathFromIDList(lpItemIDList, lpszDirectory))
		{
			if (lpszDirectory[0] == _T('\0'))
			{
				AfxMessageBox(_T("Find directory failed"),MB_ICONSTOP|MB_OK);
				return FALSE;
			}
		}
		else
		{
			AfxMessageBox(_T("Find directory failed"),MB_ICONSTOP|MB_OK);
		}

		lpMalloc->Free(lpItemIDList);
		lpMalloc->Release(); 		
	}

	return TRUE;
}

// cum il folosesti

CString str;
LPSTR buf = str.GetBuffer(MAX_PATH);
BOOL bRet = BrowseForFolder(NULL, _T("Select folder"), buf);
str.ReleaseBuffer();

Re: Cum selectez un folder?

Posted: 17 Jul 2007, 21:43
by cristitm
Mersi de cod. Merge. :yahoo:

Re: Cum selectez un folder?

Posted: 17 Jul 2007, 22:14
by Ovidiu Cucu
Hop si eu la spartu' targului! :)
Facand diverse giumbushlucuri, pana la urma poti sa selectezi un folder si cu CFileDialog.
Totusi, "calea dreapta", desi mai putin "MFC"-ista, este cea de mai sus.

Marius, lipeste-o te rog la FAQ-uri!