Displaying the Save As Common Dialog

You can use the GetOpenFileName() API function to display the Save As common dialog.  This process is exactly what the TSaveDialog component wraps.  All that's required is the initialization of an OPENFILENAME structure and a single call to GetOpenFileName().  This is virtually identical to the method for displaying an Open As dialog box.

KEYWORDS: GetOpenFileName(), OPENFILENAME. 
 



 

//---------------------------------------------------------------------------

bool ShowSaveDialog(HWND HWndOwner, char *FileName, char *Title,
    char *InitialDir, char *Filter)
{
    OPENFILENAME ofn;
    ZeroMemory(&ofn, sizeof(OPENFILENAME));

    char szFile[MAX_PATH];
    ZeroMemory(szFile, MAX_PATH);

    // Initialize OPENFILENAME
    ofn.lStructSize = sizeof(OPENFILENAME);
    ofn.hwndOwner = HWndOwner;
    ofn.lpstrFile = szFile;
    ofn.nMaxFile = MAX_PATH;
    ofn.lpstrFilter = Filter;
    ofn.nFilterIndex = 0;
    ofn.lpstrTitle = Title;
    ofn.lpstrInitialDir = InitialDir;
    ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST;

    // Display the Save dialog box.
    if (GetSaveFileName(&ofn))
    {
        strcpy(FileName, ofn.lpstrFile);
        return true;
    }
    return false;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::SaveButtonClick(TObject *Sender)
{
    char FileName[MAX_PATH];
    if (ShowSaveDialog(Handle,
                       FileName,
                       "API Save Dialog",
                       "C:\\Windows\\Desktop",
                       "Text Files (*.txt)\0*.txt\0" 
                       "Zip Files (*.zip)\0*.zip\0"
                       "All Files (*.*)\0*.*\0"))
    {
        ::MessageBox(Handle, FileName, "selected file: ", MB_OK);
    }

}