フォルダーを選択する Programming Tips Top

#include "winnetwk.h"
#include "shlobj.h"


int CALLBACK SHBrowseProc(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
{
    if ( uMsg == BFFM_INITIALIZED && lpData ) {
        SendMessage( hWnd, BFFM_SETSELECTION, TRUE, lpData);
    }
    return 0;
}


void _SHFree(ITEMIDLIST* pidl)
{
    IMalloc*  pMalloc;
    SHGetMalloc( &pMalloc );
    if ( pMalloc )  {
        pMalloc->Free( pidl );
        pMalloc->Release();
    }
}


UINT GetOpenFolderName( HWND hWnd, LPCTSTR lpszDefaultFolder, LPTSTR lpszBuffer, DWORD dwBufferSize )
{
    BROWSEINFO  bi;
    ITEMIDLIST*  pidl;
    char  szSelectedFolder[MAX_PATH];

    ZeroMemory( &bi, sizeof( BROWSEINFO ));
    bi.hwndOwner = hWnd;
    bi.lpfn      = SHBrowseProc;
    bi.lParam    = (LPARAM)lpszDefaultFolder;
    bi.lpszTitle = "フォルダを選択してください";
    pidl = SHBrowseForFolder( &bi );
    if ( pidl ) {
        SHGetPathFromIDList( pidl, szSelectedFolder );
        _SHFree(pidl);
        if( (DWORD)lstrlen(szSelectedFolder) < dwBufferSize )
            lstrcpy( lpszBuffer, szSelectedFolder );
        return IDOK;
    }
    return IDCANCEL;
}


■ 使い方

    char  szFolder[MAX_PATH];
    CString sDir;

    if ( GetOpenFolderName( m_hWnd, "c:\\", szFolder, MAX_PATH ) != IDOK ) {
        return;
    }

    sDir = (CString)szFolder;
    SetDlgItemText(IDE_EDIT, sDir );       
       
         
            


Copyright (C) CRIMSON Systems