Displaying the Open As Common Dialog

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

KEYWORDS: GetOpenFileName(), OPENFILENAME. 
 



 

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

bool ShowOpenDialog(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 Open dialog box.
    if (GetSaveFileName(&ofn))
    {
        strcpy(FileName, ofn.lpstrFile);
        return true;
    }
    return false;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::OpenButtonClick(TObject *Sender)
{
    char FileName[MAX_PATH];
    if (ShowOpenDialog(Handle,
                       FileName,
                       "API Open 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);
    }

}