PlanetSquires Forums

Please login or register.

Login with username, password and session length
Advanced search  

Author Topic: AfxExtractResourceToFile  (Read 12 times)

Paul Squires

  • Administrator
  • Master Member
  • *****
  • Posts: 8700
  • Windows 10
    • PlanetSquires Software
« on: January 20, 2019, 08:03:30 PM »

Hi Josť,

I couldn't find a function in WinFBX that extracts a resource to a file so I stole some of your other code and put together the code below. Maybe you'll find it useful and include it in the library at some point.

I needed such a function because as you've noted in your CImageCtx control some image types can't be loaded from a resource. I created a PictureBox control for the WinFBE visual designer and it extracts the image to a temp file and uses the LoadImageFromFile function that works well loading the different file types.

Code: [Select]
function AfxExtractResourceToFile( byval hInstance as HINSTANCE, _
                                   byref wszResourceName as wstring, _
                                   byref wszFileName as wstring, _
                                   byval lResourceType as LPWSTR _
                                   ) as boolean
   ' Default that the function is successful
   dim AS LONG lResult = true
   ' // Find the resource and lock it
   DIM hResource AS HRSRC = FindResourceW(hInstance, wszResourceName, CAST(LPCWSTR, lResourceType))
   IF hResource = NULL THEN RETURN false
   DIM imageSize AS DWORD = SizeofResource(hInstance, hResource)
   IF imageSize = 0 THEN RETURN false
   DIM pResourceData AS LPVOID = LockResource(LoadResource(hInstance, hResource))
   IF pResourceData = NULL THEN RETURN false
   ' // Allocate memory to hold the image
   DIM hGlobal AS HGLOBAL = GlobalAlloc(GMEM_MOVEABLE, imageSize)
   IF hGlobal THEN
      ' // Lock the memory
      DIM pGlobalBuffer AS LPVOID = GlobalLock(hGlobal)
      IF pGlobalBuffer THEN
         ' // Copy the image from the resource file to global memory
         memcpy pGlobalBuffer, pResourceData, imageSize

         AfxDeleteFile( wszFileName )
         dim as long f = freefile
         if open( wszFileName, for binary, as #f ) = 0 then
            dim pBuffer as byte ptr = pGlobalBuffer
            put #f, , pBuffer[0], imagesize       
            close #f
            return true
         end if
         ' // Unlock the memory
         GlobalUnlock pGlobalBuffer
      END IF
      ' // Free the memory
      GlobalFree hGlobal

   function = lResult
end function
Paul Squires
PlanetSquires Software
WinFBE Editor and Visual Designer