cwinapigetopenfilename

Can GetOpenFileName limit the file selection to files that match the filter?


I'm using GetOpenFileName with an OPENFILENAME structure that uses lpstrFilter to filter the files to *.JPG. However, in the file open dialog, for the File name, the user can type in *.XLS and see every Excel file in the same folder and choose to open an XLS file. I want to prevent the user from doing this. I want to really restrict them to only being able to pick JPG files for example. Is there a way to do this?


Solution

  • In the OPENFILENAME struct, enable the OFN_EXPLORER and OFN_ENABLEHOOK flags, and provide a pointer to an Explorer-style callback function in the lpfnHook field. When the callback receives the CDN_FILEOK notification, you can validate the entered file(s) (not just the filename(s), but even the actual file content, if so desired) and then return an appropriate return value to accept/reject the selection:

    If the hook procedure returns zero, the dialog box accepts the specified file name and closes.

    To reject the specified file name and force the dialog box to remain open, return a nonzero value from the hook procedure and call the SetWindowLong function to set a nonzero DWL_MSGRESULT value.