2

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?

Sean N.
  • 963
  • 2
  • 10
  • 23
  • 3
    I don't think there's a way; but even it there was, then nothing will stop the user from renaming an xls file to jpg. Or to open a broken jpeg downloaded on a flaky connection or saved on a broken USB key. The filter list is just a convenience to help the user to pick the "right" files, if he wants to feed your application garbage there's always a way. Ultimately, you'll always need to have code that handles gracefully the fact that the file that has been given to you isn't actually what you expect. – Matteo Italia May 01 '17 at 20:07
  • Thanks @MatteoItalia – Sean N. May 01 '17 at 20:17

1 Answers1

5

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770