Getting Valid Filenames

The dialog box to open a file would be much simpler if it did not contain an edit control. The edit control forces the dialog box procedure into doing some filename parsing. Much of this logic occurs when FileOpenDlgProc processes the WM_COMMAND message with wParam equal to IDOK. (When the user double-clicks a list box filename, the dialog procedure transfers the name to the edit box and then generates a WM_COMMAND message with wParam equal to IDOK. This avoids repeating the parsing logic for a list box double-click message.)

The dialog box procedure uses GetDlgItemText to obtain the string in the edit control. The parsing logic begins with a check to determine if the last character in this string is a backslash or colon. If it is, the user is requesting that the drive or directory be changed, so the current file specification must be appended to the string the user entered. If the resultant filename string contains a global character (* or ?), the dialog box procedure calls DlgDirList with the new specification, and the dialog box procedure exits to wait for the next message.

If the character string entered by the user neither terminates with a backslash or colon nor contains a global character, it could be either a directory name or a filename. FileOpenDlgProc appends a backslash and the current file specification to it. If DlgDirList doesn't report an error, processing of the message is over. Otherwise, the entered text string is probably a filename, in which case FileOpenDlgProc strips off the previously appended file specification and calls OpenFile. If OpenFile does not find the file, then the default extension is added, and OpenFile tries again. If either one of these OpenFile calls is successful in opening the file for reading, then the szPathName field of the OFSTRUCT structure is used to obtain the filename without any drive or subdirectory, and the dialog box is terminated. Otherwise, the dialog procedure beeps to indicate an error in the filename.

The FILEDLG.C file contains alternate strchr and strrchr functions that search for characters when parsing filename strings. These alternate functions use AnsiNext and AnsiPrev to allow multibyte characters in the filename strings.