Introduction
This article will make the beginner walk through the process of adding an HTML resource to their project and accessing that resource through code. What I present here is a simple function that will fill a CString
with the contents of an HTML resource.
Background
A few days ago, I was coding up this application that generates an HTML report and wanted to add the template for the report to my code. I wanted to avoid hard-coding any HTML and I didn't want to refer an external file for the template. So I decided to solve this dilemma by adding the HTML template to my project as a resource. Well, as it turns out, I was able to load the resource and get a HANDLE
to it, but couldn't figure out how to get the contents into a CString
. My fundamental problem was that I did not realize the HANDLE
was actually a bald pointer to the HTML I had loaded.
This seemingly simple task was racking my brain for nearly an hour before help arrived via the VC++ forum. I then decided to throw this stuff together in order to serve as a reference for anyone else who may run into this.
Adding an HTML Resource to your Project
Once you have created a project, you can insert an HTML resource by right-clicking the project item found in the resource tab and selecting "Add Resource" as illustrated below:
You will then be prompted to select the resource type. Select HTML and you may choose to create a New one or Import an existing file.
Once you have your HTML in your project, you're ready to access it through your program.
The GetHTML() Function
static bool GetHTML(const int& idrHTML, CString& rString)
{
bool retVal = false;
try
{
HRSRC hSrc = FindResource(NULL, MAKEINTRESOURCE(idrHTML), RT_HTML);
if (hSrc != NULL)
{
HGLOBAL hHeader = LoadResource(NULL, hSrc);
if (hHeader != NULL)
{
LPCTSTR lpcHtml = static_cast<LPCTSTR>(LockResource(hHeader));
if (lpcHtml != NULL)
{
rString = CString(lpcHtml);
retVal = true;
}
UnlockResource(hHeader);
}
FreeResource(hHeader);
}
}
catch (CMemoryException* e)
{
SetLastError(ERROR_FUNCTION_FAILED);
e->ReportError();
e->Delete();
retVal = false;
}
catch (CResourceException* e)
{
SetLastError(ERROR_FUNCTION_FAILED);
e->ReportError();
e->Delete();
retVal = false;
}
catch (CException* e)
{
SetLastError(ERROR_FUNCTION_FAILED);
e->ReportError();
e->Delete();
retVal = false;
}
catch (...)
{
SetLastError(ERROR_FUNCTION_FAILED);
retVal = false;
}
return retVal;
}
Well, that's really all there is to it.
Conclusion
I understand that, all of this may seem second-nature to many seasoned developers, but sometimes the obvious is not-so-obvious. Hopefully this little snippet helps you out in your project.
History
- 10.July.2005
Initial release.