LoadMemory example for C++ Builder
This example uses Windows API calls to load a file into memory, then uses the LoadMemory method to load the memory-resident file into a bitmap.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
HGLOBAL hMem;
int hf, iSize;
void *lpMem=0;
// Load the file into memory.
hf = FileOpen("c:\\lead\\images\\image1.cmp", fmOpenRead);
if(hf == HFILE_ERROR)
{
MessageDlg("Error opening file!", mtError, TMsgDlgButtons() << mbOK, 0);
goto quit_loadmemory;
}
iSize = FileSeek(hf, 0, 2);
FileSeek(hf, 0, 0);
hMem = GlobalAlloc(GMEM_MOVEABLE, iSize);
if(hMem == 0)
{
FileClose(hf);
MessageDlg("Not enough memory to hold the file in memory!", mtError, TMsgDlgButtons() << mbOK, 0);
goto quit_loadmemory;
}
lpMem=GlobalLock(hMem);
if(!lpMem)
{
FileClose(hf);
GlobalFree(hMem);
MessageDlg("Not enough memory to hold the file in memory!", mtError, TMsgDlgButtons() << mbOK, 0);
goto quit_loadmemory;
}
if(FileRead(hf, lpMem, iSize) < iSize)
{
FileClose(hf);
GlobalUnlock(hMem);
GlobalFree(hMem);
MessageDlg("Error reading file!", mtError, TMsgDlgButtons() << mbOK, 0);
goto quit_loadmemory;
}
GlobalUnlock(hMem);
FileClose(hf);
//Load the bitmap from the memory-resident file.
if(Lead1->LoadMemory((int)hMem, 0, 0, iSize) != SUCCESS)
MessageDlg ("Error calling LoadMemory", mtError, TMsgDlgButtons() << mbOK, 0);
else
MessageDlg ("LoadMemory succeeded", mtInformation, TMsgDlgButtons() << mbOK, 0);
GlobalFree(hMem);
quit_loadmemory:
}