본문 바로가기

C / C++ / Win32 / MFC

CFileDialog 에서 "내컴퓨터"를 초기 폴더로 지정하기


CString sf_GetComputerDir()
{
    IMalloc                *pShellMalloc            =    NULL;
    IShellFolder        *psfParent;
    LPITEMIDLIST        pidlItem                =    NULL;
    LPITEMIDLIST        pidlRelative            =    NULL;
    STRRET                str;
    WCHAR                szDisplayName[MAX_PATH]    =    L"";
    WCHAR                szPath[MAX_PATH]        =    L"";

    HRESULT hres = SHGetMalloc(&pShellMalloc);
    if (FAILED(hres))
        return _T("");

    hres = SHGetSpecialFolderLocation(NULL, CSIDL_DRIVES, &pidlItem);
    if (SUCCEEDED(hres))
    {
        hres = SHBindToParent(pidlItem, IID_IShellFolder, (void**)&psfParent, (LPCITEMIDLIST*)&pidlRelative);
        if (SUCCEEDED(hres))
        {
            memset(&str, 0, sizeof(str));
            hres = psfParent->GetDisplayNameOf(pidlRelative, SHGDN_NORMAL, &str);
            if (SUCCEEDED(hres))
                StrRetToBuf(&str, pidlItem, szDisplayName, ARRAYSIZE(szDisplayName));

            memset(&str, 0, sizeof(str));
            hres = psfParent->GetDisplayNameOf(pidlRelative, SHGDN_NORMAL | SHGDN_FORPARSING, &str);
            if (SUCCEEDED(hres))
                StrRetToBuf(&str, pidlItem, szPath, ARRAYSIZE(szPath));

            psfParent->Release();
        }
    }

    if (pidlItem)
        pShellMalloc->Free(pidlItem);
    pShellMalloc->Release();

    return szPath;
}



     CFileDialog            dlg(FALSE, _T("rtf"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
                                       _T("*.*|*.*||"));

    dlg.m_ofn.lpstrInitialDir = sf_GetComputerDir();
    if(dlg.DoModal() ==  IDOK)
    {
        m_sPath = dlg.GetPathName();
    }