Copying File Names from Explorer

This code helps you to get a set of file names & use them any time while coding or documenting. When only one filename is required, you generally tend to manually type that filename yourself. However, when more than one filename is required to be typed, you may either try to type all of the filenames or use some other means like DOS-Prompt's "dir /b" command and copy and paste them into your text. Here is one easy way to copy and paste a selection of filenames from Explorer.

The code is simple and easy to use. You just simply invoke Explorer or the Open File Dialog box. After selecting the desired files, click the right mouse button and select 'Copy'.

Windows does not actually copy the file contents into the clipboard. It just stores name references to those files in the clipboard. This code is then used to extract those filenames.

If you verify the clipboard formats when you select files from Explorer, Windows stores around eight formats with different names. CF_HDROP is one of them. This format gives you a handle with which you can query the names of all the selected files. There are other formats which give you only the name of the first file.


COleDataObject odj;
if( odj.AttachClipboard() )
{
 if( odj.IsDataAvailable( CF_HDROP ) )
 {
  STGMEDIUM StgMed;
  FORMATETC fmte = { CF_HDROP, (DVTARGETDEVICE FAR *)NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  if( odj.GetData( CF_HDROP, &StgMed, &fmte ) )
  {
   HDROP hdrop = (HDROP)StgMed.hGlobal;
   UINT cFiles = ::DragQueryFile(hdrop, (UINT)-1, NULL, 0);

   CString szText;
   szText.Format( "There are %d files/directories\r\n", cFiles );

   char szFile[MAX_PATH];

   for( UINT count = 0; count < cFiles; count++ )
   {
    ::DragQueryFile(hdrop, count, szFile, sizeof(szFile));
    szText += szFile;
    szText += "\r\n";
   }
   if (StgMed.pUnkForRelease)
   {
    StgMed.pUnkForRelease->Release();
   }
   else
   {
    ::GlobalFree(StgMed.hGlobal);
   }
  }
 }
}


Download demo project - 120 KB

Date Last Updated: February 5, 1999