Search code examples
c++winapiopenfiledialogsavefiledialog

How to restrict FileDialog to specific path


Is it possible to restrict a file dialog(open/save) to a specific folder is winapi?

OPENFILENAME fileDialogSettings;
...
fileDialogSettings.lpstrInitialDir = "Some path";
...
if(GetOpenFileName(&fileDialogSettings))
{
}

I want to have "Some path" as root path in the dialog and to restrict navigation to this folder and it's sub folders only. May I use lpfnHook for this?


Solution

  • If you're targeting Vista+ only, you can make use of the IFileDialogEvents::OnFolderChanging method to block the change altogether.

    For older versions of Windows, the OpenFileDialog allows you to specify a hook procedure in which you can pick up on the CDN_FOLDERCHANGE notification. While I can't see any message to disallow the change, you may be able to post a message to tell it to go "back", or just disable the "OK" button.

    Another option is to handle CDN_FILEOK notification and refuse paths outside your required directory.

    See this MSDN article for more details about the hook procedure. This question also talks about changing the directory in an open dialog.