Error when changing HTML of IE
Hi there,
I wrote a piece of code to change the HTML source of the current
window of IE in runtime.
USES_CONVERSION;
CoInitialize( NULL );
hInst = ::LoadLibrary( _T("OLEACC.DLL") );
pfObjectFromLresult = (LPFNOBJECTFROMLRESULT)::GetProcAddress( hInst,
_T("ObjectFromLresult") );
nMsg = ::RegisterWindowMessage( _T("WM_HTML_GETOBJECT") );
void ChangeHTML(HWND hWndChild, LPSTR HTMLCode)
{
if ( hInst != NULL )
{
if ( hWndChild )
{
LRESULT lRes;
::SendMessageTimeout( hWndChild, nMsg, 0L, 0L, SMTO_ABORTIFHUNG,
1000, (DWORD*)&lRes );
if ( pfObjectFromLresult != NULL )
{
HRESULT hr;
// spDoc is IHTMLDOcuments
hr = (*pfObjectFromLresult)( lRes, IID_IHTMLDocument, 0,
(void**)&spDoc );
if ( SUCCEEDED(hr) )
{
if (spDoc)
{
CComQIPtr< IPersistStreamInit, &IID_IPersistStreamInit >
spPSI( spDoc );
CComPtr< IStream > spStream;
hr = CreateStreamOnHGlobal( HTMLCode, TRUE, &spStream );
if ( SUCCEEDED(hr) )
{
spPSI->InitNew();
// additional code for handling the dirty data
// ULONG dwLength = strlen(HTMLCode);
// ULARGE_INTEGER uzSize = {dwLength};
// spStream->SetSize( uzSize );
spPSI->Load( spStream );
spDoc->close();
if (spPSI) spPSI.Release();
if (spStream) spStream.Release();
}
}
}
}
}
}
} // end ChangeHTML
if (hInst) ::FreeLibrary( hInst );
CoUninitialize();
One can change the content of the current window of IE by calling
ChangeHTML().
So far, everything is fine except that when one jump to other window
and replace the content of that window with some HTML shorter than
before, it occurs some dirty data at the end of the HTML. I think the
dirty data is coming from the IStream, which contains some uncleaned
data. For solving the problem, someone suggest me to resize the
IStream before it's being loaded into IPersistStreamInit. That's where
the following code come from
ULONG dwLength = strlen(HTMLCode);
ULARGE_INTEGER uzSize = {dwLength};
spStream->SetSize( uzSize );
However, the extra code for limit the size of the stream seems not
perfect for solving the problem. Suppose I open two windows in IE. For
the first time, I change the HTML of the first window; it's all right.
Then, I jump to the second window, change the content with a HTML
shorter than before(that will incur the dirty data), and the
additional code does solve the problem and clear the dirty data.
However, when I come back to the first window and change the HTML
again with anything, it crashes! The problem repeats unless getting
rid of the additional code. What's going on? Any idea to solve the
troube?
Thanks in advance.