Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Web Win32/WTL Hybrid

0.00/5 (No votes)
22 Dec 2005 1  
How to implement a two-way communication path from IExplorer and WTL code

Introduction

Normally, when we see applications like, for instance, MS Money, that looks like an Internet Explorer layout and has the functionality of a Win32 application, we don't know if Microsoft guys are hiding some technical concepts from us, (I don't know any, I promise you ;) ), or maybe we can't read Microsoft MSDN documentation properly than they can.

This article will expose the way to fully reuse IExplorer for your applications, and will try to explain the implementation of this sample. In fact, it is a sample and is not a "real" library to be used in a "real" application. I only want to show one way to do this kind of implementations. The code has no full error handling, so if you want to use it in a "real" application, keep in your mind, you will need to review some of the critical steps.

Before taking on the next sections, I invite you to get the sample source code, and compile it, I think it will be great for you to understand the following sections better.

Compiling

There are two versions of the code, one for VC6/WTL7.0 and the other for VC7/WTL7.0.

You should have installed the latest Platform SDK or you will receive errors in interface declarations like IHTMLElement2.

You can find the Platform SDK as a free download at msdn.microsoft.com.

Once you compile the program, you might receive a "library not registered" error; if this occurs, you only need to go to the project directory and execute RegTLib WebWin32Sample.tlb. Sometimes, you might need to register the COM server in this way: WebWin32Sample.exe /RegServer, run both only once.

Final class

First of all, I want to show you how the "host" class looks, and then I will explain each piece of code and the underlying tricks:

class CWebWin32SampleView : public 
                CWindowImpl<CWebWin32SampleView,CAxWindow>
{
public:
    DECLARE_WND_SUPERCLASS(NULL, CAxWindow::GetWndClassName())

    // Our internet explorer control

    CWTLIExplorer m_pBrowser;

    // Our vars to Exchange information with HTML page...

    CString m_FirstName;
    CString m_LastName;
    CString m_Address;
    CString m_Country;
    BOOL m_ILikeThisSample;

    // html-hosted-page-form-based DDX

    BEGIN_HTML_DDX()
        BEGIN_FORM( "testForm" ) // Our Form Name ( at HTML page )

          // Our exchange definitions...

          DDX_HTML_STRING( m_FirstName ,"firstName" ) 
          DDX_HTML_STRING( m_LastName  ,"lastName" )
          DDX_HTML_STRING( m_Address,"address" )
          DDX_HTML_LISTBOX( m_Country, "country" );
          DDX_HTML_CHECKBOX( m_ILikeThisSample, "ILikeIt" )
       END_FORM()
     END_HTML_DDX()

    // HTML Handlers

    // Here we can define HTML handlers hooks related to element at the 

    // page loaded

    BEGIN_HTML_MSG_MAP(CWebWin32SampleView,m_pBrowser)
        // Set an event handler on buttonSumbmit.onclick 

        COMMAND_HTML_HANDLER( ID_HTML_CLICK, "buttonSubmit", OnSubmit )
    END_HTML_MSG_MAP()

    LRESULT OnSubmit( BOOL & bHandled )
    {
        // Do Data Exchange with HTML page...

        DDX_HTML_EXCHANGE( m_pBrowser, false /* false=get | true=set */ )

        // MessageBox text Composite 

        CString totalMessage = m_FirstName + CString(" - ") + m_LastName + 
                                                CString(" - " ) + m_Address;

        if ( m_ILikeThisSample )
             totalMessage += CString("\n\nYou have checked it." );
        else
             totalMessage += CString("\n\nYou have not checked it." );

        totalMessage += CString("\n\nCountry Selected: ") + m_Country;

        // Show a message box

        MessageBox( totalMessage,
                "From CWebWin32SampleView::OnSubmit event handler.", 
                MB_ICONINFORMATION );

        // set handled

        bHandled = true;
 
        return 0;
    }


    BOOL PreTranslateMessage(MSG* pMsg);

    BEGIN_MSG_MAP(CWebWin32SampleView)
        MESSAGE_HANDLER(WM_CREATE, OnCreate)
        MESSAGE_HANDLER(WM_SIZE, OnSize)

        // We receive this message when IExplorer is on a ready state for us

        // and we can Set handlers to the page...

        MESSAGE_HANDLER(WM_HTML_SETHANDLERS /* = WM_USER + 1 */ , 
                                                OnHTMLSetHandlers )
    END_MSG_MAP()

    LRESULT OnHTMLSetHandlers(UINT /*uMsg*/, WPARAM /*wParam*/, 
                            LPARAM /*lParam*/, BOOL& /*bHandled*/ )
    {
        // Activate event handlers map

        SET_HTML_MESSAGE_MAP();
        return 0;
    }

// Handler prototypes (uncomment arguments if needed):

// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, 

//                         LPARAM /*lParam*/, BOOL& /*bHandled*/)

// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, 

//                         HWND /*hWndCtl*/, BOOL& /*bHandled*/)

// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, 

//                                         BOOL& /*bHandled*/)


    LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, 
                    LPARAM /*lParam*/, BOOL& /*bHandled*/);
    LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, 
                    LPARAM /*lParam*/, BOOL& /*bHandled*/);
};

BEGIN_HTML_MAP() ... END_HTML_MAP()

In fact, all HTML elements at IExplorer derive from IHTMLElement. In this interface, we can find the possibility to use some methods to get/set event handlers at element level, like put_onclick( VARIANT handler), the variant should hold a VT_IDISPATCH variable that references a COM object. When this event is fired, IExplorer tries to call the default method of this IDispatch object. This is perfect for our intentions, so we need to define a COM object that holds a default method, when this method is called we only need to "jump" into our event handler.

The object I use to do this work is WebWin32.WebWin32EventHandler that has only two methods SetHandler(LONG,LONG) and CallHandler which is the object's default method.

SetHandler(LONG,LONG) is called to set the "callback" address. To do this, we need to pass our object address (this) and the member address callback entry point.

We need to do some code level "crack" to convert the Pointer member variable which holds the member address into a LONG.

// ( This is a simulation )

[...]
DWORD pointer_part_2 = (DWORD) this;
DWORD pointer_part_1;
[...]

// pointer member prototype

LRESULT (CWebWin32SampleView::*pVar) ( BOOL & );

// load our member pointer

pVar = OnSubmit;

// extract address

memcpy( &pointer_part_1, ( char * )  &pVar, 4 );
[...]
pHandler->SetHandler( pointer_part_1, pointer_part_2 );
[...]
SetHandlerIntoHtmlElementOnClick( pHandler, "addressField" );
[...]

Later, when IExplore fires our method, we need to do another "trick" to "jump" into our "callback":

STDMETHODIMP CWebWin32EventHandler::CallHandler(void)
{
    // __thiscall asm implementation


    DWORD pMember;
    DWORD pThis;

    pThis   = m_pThis;
    pMember = m_pMember;

    BOOL bHandled=false;
        
    // this the same like do pObject->MemeberToCall( bParam ) 

    // but we don't have

    // problems about what type of object or method prototype was defined, 

    // this is a generic "thiscall"

    _asm
    {
        lea eax,      ; BOOL & 
        push eax                ; push it
        mov ecx,[pThis]         ; "this" object into ecx
        call pMember            ; call the member pointer
    }
    return S_OK;
}

That is all we need to know to fire events from an HTML element to our code.

BEGIN_HTML_DDX() ... END_HTML_DDX()

As we have a reference to the IExplorer instance, this is the easiest of the things, we only need to query the current document's collections to find the correct element and query for the value at it.

Web -> Win32 Path

As you have seen in the sample, by pushing an HTML button, you can hide/show a treeview, set the status bar text, and so on.

Well, we can do this work in two ways, using handlers as described above, or using another technique:

You can put an object reference (COM Object Dual Interface) using the CAxWindow::SetExternalDisptach() method. Once you have put a reference to this method, you can access methods of this object using script code at the Explorer page level external.MyMethod)().

The steps needed to do this are:

EVENTFN CWTLIExplorer::OnDocumentComplete( IDispatch* pDisp,  VARIANT* URL )
{
    [.....]

    CAxWindow::SetExternalDispatch( (IDispatch*) _Module.m_LibraryObject );

    // ignore about:blank

    if ( _bstr_t( bstrLocation ) != _bstr_t("about:blank") )
        // Notify parent window we are ready and loaded...

    CWindow(GetParent()).SendMessage( WM_HTML_SETHANDLERS ,0,0 );

}

Once you have set the main object library, as you can see at the sample.html script code, you can do calls to the methods:

<script>
     [...]
     window.external.MyMessageBox "Hello!","Bye!"
     [...]
     window.external.HideTree() 
     [...]
     window.external.ShowTree() 
     [...]
     window.external.statusbartext = text
     [...]
     window.external.AddChildToTree( window.document.all("newitem").value )
</script>

You can use VBScript or JScript, there is no problem.

Closing words

I'm sure I will update this article soon, so any comment will be appreciated.

Well, that's all, I expect you find this article useful and helpful. If you think you have found anything wrong, feel free to contact me or solve it by yourself, I will be very happy to fix anything. Bye!!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here