Windows 7 Libraries and the Common File Dialog…

As you can read in the application cookbook:

When using IFileDialog, you must use GetResult method instead of combination of GetFolder and GetFilename. Use the Shell APIs where possible to interact with and manipulate items in the Shell Namespace (for example, IShellItem).

So let me share a small code snippet I wrote. Hopefully, this will help you.

Here is how the execution looks like on my machine (Windows 7 Beta 1):

 image

image

And now the code snippet:

#include <comdef.h>
#include <shlobj.h>

_COM_SMARTPTR_TYPEDEF(IFileOpenDialog, __uuidof(IFileOpenDialog));
_COM_SMARTPTR_TYPEDEF(IShellItem, __uuidof(IShellItem));

#include <sstream>
using std::endl;
using std::wostringstream;

const wchar_t NullString[] = L"(NULL)";

void FileOpen(HWND window) {
   IFileOpenDialogPtr fileOpenDialog(__uuidof(FileOpenDialog));
   fileOpenDialog->SetTitle(L"Select any file under a Library");
   FILEOPENDIALOGOPTIONS fileOpenDialogOptions;
   fileOpenDialog->GetOptions(&fileOpenDialogOptions);
   fileOpenDialogOptions ^= FOS_FILEMUSTEXIST;
   fileOpenDialog->SetOptions(fileOpenDialogOptions);
   if (fileOpenDialog->Show(window) == HRESULT_FROM_WIN32(ERROR_CANCELLED))
      return;

   LPWSTR filename = NULL;
   fileOpenDialog->GetFileName(& filename);
   IShellItemPtr folderShellItem;
   fileOpenDialog->GetFolder(& folderShellItem);
   LPWSTR folderShellItemName = NULL;
   folderShellItem->GetDisplayName(SIGDN_FILESYSPATH, & folderShellItemName);

   IShellItemPtr resultShellItem;
   fileOpenDialog->GetResult(& resultShellItem);
   LPWSTR resultShellItemName = NULL;
   resultShellItem->GetDisplayName(SIGDN_FILESYSPATH, & resultShellItemName);

   wostringstream b;
   b << L"IFileOpenDialog::GetFileName():" << endl << (filename ? filename : NullString) << endl << endl
     << L"IShellItem::GetDisplayName() on IFileOpenDialog::GetFolder():" << endl << (folderShellItemName ? folderShellItemName : NullString) << endl << endl
     << L"IShellItem::GetDisplayName() on IFileOpenDialog::GetResult():" << endl << (resultShellItemName ? resultShellItemName : NullString);

   CoTaskMemFree(filename);
   CoTaskMemFree(folderShellItemName);
   CoTaskMemFree(resultShellItemName);

   MessageBox(GetDesktopWindow(), b.str().c_str(), L"Results of dialog", MB_OK);
}

Voilà.

Resources:

Windows 7: Empower users to find, visualize and organize their data with Libraries and the Explorer

Windows Application Quality Cookbook