I did not see the source for the heap error but you also asked for the right or simpler way. At first you should know that the HTML clipboard format must contain UTF-8 encoded text. So the input text must be converted to UTF-8 and prefixed with the HTML format header. A snippet from one of my projects (
lpszWide
is the HTML text as wide string including the HTML and fragment start and end markers):
int nUtf8Size = ::WideCharToMultiByte(CP_UTF8, 0, lpszWide, -1, NULL, 0, NULL, NULL);
if (nUtf8Size < 1)
{
TRACE0("CHtmlFormat::SetHtml: UTF-8 conversion failed\n");
ASSERT(0);
return false;
}
const int nDescLen = 105;
hGlobal = ::GlobalAlloc(GMEM_MOVEABLE, nDescLen + nUtf8Size);
if (NULL != hGlobal)
{
bool bErr = false;
LPSTR lpszBuf = static_cast<LPSTR>(::GlobalLock(hGlobal));
LPSTR lpszUtf8 = lpszBuf + nDescLen;
if (::WideCharToMultiByte(CP_UTF8, 0, lpszWide, -1, lpszUtf8, nUtf8Size, NULL, NULL) <= 0)
{
TRACE0("CHtmlFormat::SetHtml: UTF-8 conversion failed\n");
bErr = true;
}
else
{
LPCSTR lpszStartFrag = strstr(lpszUtf8, "<!--StartFragment-->");
LPCSTR lpszEndFrag = strstr(lpszUtf8, "<!--EndFragment-->");
ASSERT(lpszStartFrag);
ASSERT(lpszEndFrag);
lpszStartFrag += strlen("<!--StartFragment-->") + 2;
VERIFY(nDescLen == _snprintf(
lpszBuf, nDescLen,
"Version:1.0\r\nStartHTML:%010d\r\nEndHTML:%010d\r\nStartFragment:%010d\r\nEndFragment:%010d\r\n",
nDescLen,
nDescLen + nUtf8Size - 1,
nDescLen + static_cast<int>(lpszStartFrag - lpszUtf8),
nDescLen + static_cast<int>(lpszEndFrag - lpszUtf8)));
}
::GlobalUnlock(hGlobal);
if (bErr)
{
::GlobalFree(hGlobal);
hGlobal = NULL;
}
}
return NULL != hGlobal;