2

According to the documentation for the OPENFILENAME structure, the following algorithm is used to select the initial directory:

Windows 7:

  1. If lpstrInitialDir has the same value as was passed the first time the application used an Open or Save As dialog box, the path most recently selected by the user is used as the initial directory.
  2. Otherwise, if lpstrFile contains a path, that path is the initial directory.
  3. Otherwise, if lpstrInitialDir is not NULL, it specifies the initial directory.
  4. If lpstrInitialDir is NULL and the current directory contains any files of the specified filter types, the initial directory is the current directory.
  5. Otherwise, the initial directory is the personal files directory of the current user.
  6. Otherwise, the initial directory is the Desktop folder.

I'm using the following code to construct a file dialog:

CFileDialog dlgFile(bOpenFileDialog);
dlgFile.m_ofn.lpstrInitialDir = strSourcePath;
dlgFile.m_ofn.lpstrFile = fileName.GetBuffer(_MAX_PATH);

However, it ALWAYS opens the same default folder in strSourcePath. Does anyone know why? It should only use this directory the first time, and subsequent file opens should remember the last folder (bullet point 1. in the algorithm). I'm using VS2012 on Windows 7.

IInspectable
  • 46,945
  • 8
  • 85
  • 181
Skynight
  • 507
  • 2
  • 7
  • 24
  • 1
    The documentation seems to be conflicting. While [OPENFILENAME](https://msdn.microsoft.com/en-us/library/ms646839.aspx) contains the algorithm replicated in the question, [CFileDialog::m_ofn](https://msdn.microsoft.com/en-us/library/43xtah3y.aspx) suggests, that `lpstrInitialDir` is not supported, when using the Windows Vista style dialogs. – IInspectable Sep 21 '15 at 07:48
  • @IInspectable Apparently `lpstrInitialDir` it not ignored on Windows 10,but if I remember correctly it was ignored on Vista and Windows 7. – Jabberwocky Jun 28 '23 at 10:24

1 Answers1

-1

Here is the fix:

dlgFile.m_ofn.lpstrInitialDir = strSourcePath.GetBuffer(_MAX_PATH);

Don't forget to call strSourcePath.ReleaseBuffer(); when you done.

If you are using lpstrFile to specify filename, then you may need to prepend initial directory path to the filename.

Andrew Komiagin
  • 6,446
  • 1
  • 13
  • 23
  • Sorry, forgot to add...strSourcePath is a CString strSourcePath; strSourcePath = "C:\\Foldername"; – Skynight Sep 20 '15 at 21:33
  • 4
    That doesn't solve anything. `CString` has an implicit `LPCTSTR` conversion operator (as used in the question). `lpstrInitialDir` is of type `LPCTSTR`. Passing a pointer to a modifiable string, for no reason whatsoever, is wrong. I don't know, why you think this is a solution. – IInspectable Sep 21 '15 at 01:11