Home Search Contact us About us
Title Using CHtmlView as a control.
Summary How to add web browsing and html editing capability to an application. Also includes tips on communicating with the browser control and embedding HTML and images in your application.
Contributor Paul DiLascia
Published 11-Mar-2001
Last updated 11-Mar-2001
Page rating   94% for 61 votes Useless Brilliant
 Download demo source - 13kb

Introduction
Using CHtmlCtrl
Load from an internal Resource
Make CHtmlCtrl talk to application
How to make a HTML editor
How to modify append the page content from the app
How to view the app's resource

Introduction.

This article describes how to use a simple control to add a web browser to an application. It also goes on to show how to control the browser and enable editing. Don't forget at the very minimum you will need IE4 installed on the target system. CHtmlCtrl was created by Paul DiLascia and the full article can be found at Microsoft Systems Journal.

Using CHtmlCtrl.

  • Start by including the following headers.
#include <afxhtml.h>        // MFC support for Web browser
#include <mshtml.h>         //IWeb objects
#include <atlconv.h>        //Conversion routines
  • Add the HtmlCtrl.cpp and HtmlCtrl.h files to the project with menu option "Project->Add to Project->Files". 
  • Add a static control to a dialog and size it as required. 
  • Lets call this control IDC_STATIC_BROWSER
  • To the dialog header include the control and make an object to hold it.
#include "HtmlCtrl.h"                               //Web browser control
...
class ...
{
...
//Attributes
private:
    CHtmlCtrl   m_Browser;                          //Web browser object.
...
}
  • Next create the object and load a page in the OnInitDialog();.
    m_Browser.CreateFromStatic( IDC_STATIC_BROWSER, this );
    m_Browser.Navigate( _T("www.mctainsh.com") );

Load from an internal Resource.

We shall compile an html file and image into the application and load it at start-up. 

  • Put an html file and image in the res directory. 
  • Add the following to the app.RC2 file.
/////////////////////////////////////////////////////////////////////////////
// Add manually edited resources here...
ABOUT.HTM       HTML DISCARDABLE "res\\about.htm"
FOX.GIF         HTML DISCARDABLE "res\\fox.gif"
  • Change OnInitDialog(); to the following.
    m_Browser.CreateFromStatic( IDC_STATIC_BROWSER, this );
    m_Browser.LoadFromResource( _T("ABOUT.HTM") );

Make CHtmlCtrl talk to application.

By adding a prefix to the hyper link, the web control can call code in the application. Here app: is used as the link prefix. When CHtmlCtrl::OnBeforeNavigate2 detects this it passes the command string on to CHtmlCtrl::OnAppCmd, where actions can be performed according to the input string.

The HTML is like this.

<a href="app:JustDoIt">Make it happen</a>

Processing.

void CHtmlCtrl::OnAppCmd(LPCTSTR lpszWhere)
{
    ...
    if( _tcscmp( _T("JustDoIt"), lpszWhere )==0 ) 
    {
        RunSweatShop();
    }   
    ...

How to make a HTML editor.

This web browser control can be used to edit and create HTML with the following code. This will put the control in design mode.

    IDispatch* pDispatch = m_Browser.GetHtmlDocument();
    //Only if a resource or web page is loaded can we get the document
    if( pDispatch != NULL )
    {
        IHTMLDocument2* pHtmlDoc;
        HRESULT hr = pDispatch->QueryInterface( __uuidof( IHTMLDocument2 ), (void**)&pHtmlDoc );
        pDispatch->Release();
        if( SUCCEEDED( hr ) )
        {
            pHtmlDoc->put_designMode(L"On"); 
            pHtmlDoc->Release();
        }
    }

How to modify append the page content from the app.

It is possible to dynamically modify the content of the web browser dynamically from the application. This is done by reading the document body changing it and writing it back. The following code reads the body and adds a message to the end with the current time in it.

    IDispatch* pDispatch = m_Browser.GetHtmlDocument();
    //Only if a resource or web page is loaded can we get the document
    if( pDispatch != NULL )
    {
        IHTMLDocument2* pHtmlDoc;
        HRESULT hr = pDispatch->QueryInterface( __uuidof( IHTMLDocument2 ), (void**)&pHtmlDoc );
        pDispatch->Release();
        if( SUCCEEDED( hr ) )
        {
            //Get access to the internal document
            IHTMLElement *pElement;
            hr = pHtmlDoc->get_body( &pElement );
            if( SUCCEEDED( hr ) )
            {
                //Extract the data
                USES_CONVERSION;
                BSTR bsMainText;
                pElement->get_innerHTML( &bsMainText );
                CString sBody( OLE2T(bsMainText) );
                SysFreeString( bsMainText );

                //Append the new text
                sBody += _T("<p>Just added this line at ");
                sBody += CTime::GetCurrentTime().Format( _T("%H:%M:%S") );
                sBody += _T("</p>");

                //Assign the new text
                bsMainText = SysAllocString( T2OLE(sBody) );
                pElement->put_innerHTML( bsMainText );
                SysFreeString( bsMainText );
                pElement->Release();
            }
        }
    }

How to view the app's resource.

It is possible to view the resources compiled into an application with a web browser. For the demo application use the following line entered as the web address. 

res://D:\SRC\TryHtml\Debug\TryHtml.exe/about.htm
Comments Date
5-Dec-2001 Amit
Good Example
How print html page 26-Feb-2002 Domoro
In the following way I print my page:

void CHtmlDlg::OnPrint()
{
LPDISPATCH lpDispatch = NULL;
LPOLECOMMANDTARGET lpOleCommandTarget = NULL;

lpDispatch = m_Browser.GetHtmlDocument();
ASSERT(lpDispatch);

lpDispatch->QueryInterface(IID_IOleCommandTarget,
(void**)&lpOleCommandTarget);
ASSERT(lpOleCommandTarget);

lpDispatch->Release();

// print contents of web browser control
lpOleCommandTarget->Exec(NULL, OLECMDID_PRINT, 0, NULL,NULL);

lpOleCommandTarget->Release();

// CDialog::OnOK();
}
How print html page 26-Feb-2002 Domoro
In the following way I print my page:

void CHtmlDlg::OnPrint()
{
LPDISPATCH lpDispatch = NULL;
LPOLECOMMANDTARGET lpOleCommandTarget = NULL;

lpDispatch = m_Browser.GetHtmlDocument();
ASSERT(lpDispatch);

lpDispatch->QueryInterface(IID_IOleCommandTarget,
(void**)&lpOleCommandTarget);

ASSERT(lpOleCommandTarget);

lpDispatch->Release();

// print contents of web browser control
lpOleCommandTarget->Exec(NULL, OLECMDID_PRINT, 0, NULL,NULL);

lpOleCommandTarget->Release();
}

What do you think?
Bye, DoM.
compile error with .NET 3-Jun-2002 Todd
When I compile this code I get the following error.

c:\Documents and Settings\AboutHtml2\HtmlCtrl.cpp(57): error C2248: `ATL::_NoAddRefReleaseOnCComPtr<T>::Release` : cannot access private member declared in class `ATL::_NoAddRefReleaseOnCComPtr<T>`
with
[
T=IWebBrowser2
]
and
[
T=IWebBrowser2
]

I would appreciate any help to resolve this error.

Thanks,

Todd
Pop Menus 21-Aug-2002 Daniele
There is a way for disable or to customize the pop menu that come out when the user click the right button of the mouse?

Best regards
Daniele

Access Violation 13-Dec-2002 Ilkka
Hi,

When I run that program in debug mode, I see these messages:

First-chance exception in TryHtml.exe (GDI32.DLL): 0xC0000005: Access Violation.

What does this mean? Is it something to worry about?

Thanks,
Ilkka
24-Jun-2004 rdpdo
Crashhhhhh
1-Feb-2005
aaaaaaaa
21-Feb-2005 Miron Levin
I just want to say thank you. This code is very helpfull for my aplication.
Great source 23-Oct-2005 mis
How can I insert html file in an executable file like e-book generator? thanks
Great!! 13-Jan-2006 CrashbandyCoot
Exactly what I was looking for!!
Home Search Contact us About us