How to Save and Load a Windows Region with MFC

I wrote an article for CodeGuru that explains in details how to save a Windows region to a file using CRgn::GetRegionData and how to load and re-create this saved region with CRgn::CreateFromData using MFC.

There are 2 functions in the article: SaveRegion and LoadRegion. For demonstration purposes, the SaveRegion function will first create an elliptic region and will then save this region to a file. The LoadRegion function will read the data back from the file and create a Windows region from this data. For making it visually clear that the LoadRegion function has loaded the correct region, the region is set as the window region.

The SaveRegion function looks like:

// lang cpp
void SaveRegion()
{
   // Create some elliptic region as demonstration
   CRect rc;
   GetWindowRect(rc);
   CRgn rgn;
   rgn.CreateEllipticRgn(0, 0, rc.Width(), rc.Height()); 

   // Get the size in bytes of our created region
   int iSize = rgn.GetRegionData(NULL, sizeof(RGNDATA)); 

   // Allocate memory to hold the region data
   RGNDATA* pData = (RGNDATA*)calloc(iSize, 1);
   pData->rdh.dwSize = iSize; 

   // Get the region data
   int iSize2 = rgn.GetRegionData(pData, iSize);
   // Sanity check
   if (iSize != iSize2)
      AfxMessageBox(_T("Something wrong with GetRegionData...")); 

   // Save region data to a file
   CFile f(_T("test_region.rgn"), CFile::modeCreate | CFile::modeWrite);
   f.Write(pData, iSize);
   f.Close(); 

   // Free allocated memory
   free(pData);
}

The LoadRegion function looks like:

// lang cpp
void LoadRegion()
{
   // Open file to read region data from
   CFile f(_T("test_region.rgn"), CFile::modeRead); 

   // Get size of the file
   int iSize = f.GetLength(); 

   // Allocate memory to hold the region data
   RGNDATA* pData = (RGNDATA*)calloc(iSize, 1); 

   // Read region data from file
   f.Read(pData, iSize);
   f.Close(); 

   // Create region from loaded region data
   CRgn rgn;
   rgn.CreateFromData(NULL, iSize, pData); 

   // As a demonstration, set the loaded region as window region
   // so it is visually clear that it got loaded correctly.
   SetWindowRgn(rgn,TRUE); 

   // Free allocated memory
   free(pData);
}

For a more detailed explanation of all the steps in the above 2 functions, check out my article at CodeGuru: How to Save and Load a Windows Region with MFC.

Leave a Comment

Name: (Required)

E-mail: (Required) (will not be published)

Website:

Comment:

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.