Monday, January 28, 2008

Saving a Resource Item into File From Application Resource VC++

Resource files represent one of the most prominent features of Windows programming. It is through resource files that most applications define the visible elements of their user interface: menus, dialogs, text strings, bitmaps, and other types of resources.

Resource files are created in a form readable by humans and compiled with the Resource Compiler. The compiled result is usually linked with the rest of the application to form a single binary image that contains executable code and resource information.

If you add a resource item ( Bitmap, Html,…) then this will embedded into .Exe( or Dll, OCX ) file

Using Following code we can save resource files locally.

 

#include <fstream>

char* CUtility::GetResourceData(const CString& strCustomResName,int nResourceId,DWORD& nReadDataSize )
{    
      HGLOBAL hResourceLoaded;  // handle to loaded resource
      HRSRC   hRes;              // handle/ptr to res. info.
      char    *lpResLock = NULL;        // pointer to resource data
      hRes = FindResource(NULL,MAKEINTRESOURCE(nResourceId),strCustomResName);
      ASSERT(hRes != NULL);
      if( hRes != NULL)
      {
            hResourceLoaded = LoadResource(NULL, hRes);
            ASSERT(hResourceLoaded != NULL);
            if( hResourceLoaded != NULL)
            {
                  //If the loaded resource is locked, the return value is
                  //a pointer to the first byte of the resource; otherwise, it is NULL.
                  lpResLock = (char *) LockResource(hResourceLoaded);
                  nReadDataSize = SizeofResource(NULL, hRes);
                  FreeResource(hResourceLoaded);
            }
      }
      return lpResLock;
}

void CUtility:: CreateFile (const CString& strFileName,char *pData, DWORD wDatLength)

{
      if( wDatLength > 0)
      {
            std::ofstream outputFile(strFileName, ios::binary);
            outputFile.write((const char *) pData, wDatLength);
            outputFile.close();
      }
}
void CUtility::SaveResourceItemToFile(const CString& strFileName, const CString& strCustomResName,int nResourceId)
{
      DWORD dwDataLength = 0;
      char    *lpResLock = GetResourceData(strCustomResName,nResourceId,dwDataLength);
      if( dwDataLength > 0 )
      {
            CreateFile( pFileName, lpResLock, dwDataLength);                       
      }
}

Example Code:

CUtility::SaveResourceItemToFile( _T(“C:\\Sen.sql”, _T(“DMSqlData”), IDR_DMSQL_SCRIPT_DATA)

 

 

 

No comments: