To use one of the common dialog boxes that open and save files, an application must first fill out the OPENFILENAME structure, which includes the items needed to initialize the dialog box. The following example is the code I used for the Open common dialog box:
OpenFileName.lStructSize = sizeof (OPENFILENAME);
OpenFileName.hwndOwner = hWnd;
OpenFileName.hInstance = (HANDLE)hInst;
OpenFileName.lpstrFilter = szFilter;
OpenFileName.lpstrCustomFilter = (LPTSTR)NULL;
OpenFileName.nMaxCustFilter = 0L;
OpenFileName.nFilterIndex = 1L;
OpenFileName.lpstrFile = szFile;
OpenFileName.nMaxFile = sizeof (szFile);
OpenFileName.lpstrFileTitle = szFileTitle;
OpenFileName.nMaxFileTitle = sizeof (szFileTitle);
OpenFileName.lpstrInitialDir = NULL;
OpenFileName.lpstrTitle = "Open";
OpenFileName.nFileOffset = 0;
OpenFileName.nFileExtension = 0;
OpenFileName.lpstrDefExt = "*.txt";
OpenFileName.lCustData = 0;
When the structure is filled out, a call to GetOpenFileName with a pointer to the structure will display the dialog box. If the function returns a value of TRUE, no errors occurred, and the file can be opened. The filename is copied into the lpstrFile member of the OPENFILENAME structure. If the GetOpenFileName function returns FALSE, an error handler is called with the extended error (returned from the CommDlgExtendedError function):
if (GetOpenFileName (&OpenFileName))
{
// Open the file.
if ((hFile = CreateFile ((LPCTSTR)OpenFileName.lpstrFile,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
(HANDLE)NULL)) == (HANDLE)(-1))
{
MessageBox (hWnd, "File open failed.", NULL, MB_OK);
return FALSE;
}
// Read its contents into a buffer
.
§
}
else
{
// Send the error to your error handler.
ProcessCDError (CommDlgExtendedError (), hWnd);
return FALSE;
}
A wide variety of flags can be used in the Flags member of the OPENFILENAME structure. These flags allow a developer to provide functionality (such as multiple selection), to decide whether to use the Windows 3.1 or the Windows 95 look in the dialog box, and to specify that the file must exist in order to be opened. For an exhaustive list of all flags supported by the OPENFILENAME structure, refer to the Win32 SDK documentation.