Click here to Skip to main content
12,505,591 members (51,984 online)
Click here to Skip to main content
Add your own
alternative version

Stats

211K views
3.8K downloads
90 bookmarked
Posted

Handling HTML Element Events in MFC applications - A simple alternative approach

, 12 Jan 2002
Rate this:
Please Sign up or sign in to vote.
Demonstration of a simple technique to intercept and handle, HTML element events generated in a hosted WebBrowser Control
<!-- Download Links --> <!-- Article image -->

Sample Image - dhtml.gif

<!-- Add the rest of your HTML here -->

Introduction

The conventional approach to sink events when hosting a WebBrowser control involves using the MSHTML Element Events2 Interface. It requires retrieving a pointer to the element of interest of the page,  retrieving a pointer to the connection point container, finding the required connection point, advising the connection point to start receiving events, implementing IDispatch::Invoke to handle any fired event and closing the connections when no longer needed.

This article illustrates a simple alternative technique to intercept and handle, in a MFC application, HTML element events generated in a hosted WebBrowser Control. It also shows how to use xml objects to pack event information to the hosting application, and how to extract this information to implement an event handler.

Implementation

Before navigation occurs in a WebBrowser control, a BeforeNavigate2 message is fired. VC++ 6.0 MFC Class Wizard, automatically adds the appropriate OnBeforeNavigate2 member function to handle this event.

Two of the six parameters taken by OnBeforeNavigate2, are useful to intercept DHTML events: VARIANT FAR* URL that contains the url address to be navigated to, and BOOL FAR* Cancel, that cancels navigation before it occurs.

In a WebBrowser's HTML page, the VBScript property location.href of the browser document's object, sets the entire URL as a string. When a given URL is set in the HTML script event handler, the corresponding string is passed as the second parameter of the member function OnBeforeNavigate2 of the hosting application.

In order to intercept and handle HTML element events, the href property should contain, instead of a regular URL address, a string with the necessary information of the DHTML event fired in the Browser control.

In most cases, the information required by the hosting application consists of the html element's id , and an associated value. This information is packed in a xml string having the form "<element idevent='001'>value</element>".

Once this value is passed to OnBeforeNavigate2, the parameter Cancel is set to TRUE to avoid navigation. The following two code snippets illustrate these ideas.

<SCRIPT ID = "clientEventHandlersVBS" LANGUAGE="VBScript">
<!--

dim strIndex

Sub myelement_onmouseover()
    strIndex = "007"
    strXML = "<element idevent='" & strIndex & "'>" &_
 myelement.innerText & "</element>"
    location.href = "Event:" & strXML
End Sub

--> 
</SCRIPT>
// OnBeforeNavigate2 Event

handler void CDlgDHTMLEventsDlg::OnBeforeNavigate2(LPDISPATCH pDisp,
                                                   VARIANT FAR* URL,
                                                   VARIANT FAR* Flags,
                                                   VARIANT FAR* TargetFrameName,
                                                   VARIANT FAR* PostData,
                                                   VARIANT FAR* Headers,
                                                   BOOL FAR* Cancel) 
{
    CString strURL(URL->bstrVal);
    CString strXML(strURL.Right(strURL.GetLength()-6));
    strXML.Replace("%20", " ");

    if(strURL == _T("about:blank"))
        *Cancel = FALSE;
    else
    {
        ExtractXMLInfo(strXML);
        *Cancel = TRUE;
    }
}

The sample application

dlgDHTMLEvents is a dialog based MFC application. The dialog hosts a WebBrowser control that shows a HTML page having these DHTML objects: two INPUT elements, two BUTTONS, one <h1> text element and one IMAGE object. When some predetermined events are fired by each one of these elements, its id and associated value are passed to the MFC dialog app.

Since xml is used to convey DHTML event information, the Microsoft XML parser should be imported into the MFC project. To do it, add this line to StdAfx.h (If not installed, it can be downloaded from http://www.msdn.microsoft.com/downloads/default.asp ):

#import "Msxml3.dll" named_guids raw_interfaces_only

To add ATL support (CComBSTR types are used), include this header file in StdAfx.h:

#include <atlbase.h> 

The HTML script is stored as a resource of the project (ID: IDR_HTML). The script's event handlers are included in the section <SCRIPT ID = "clientEventHandlersVBS" LANGUAGE="VBScript">of this resource.

The page is loaded into the Browser using the IPersistStreamInit interface and associated methods, of the CWebBrowser2 class. The member function LoadHTMLPage(CString strBaseAddress) implements this operation. The strBaseAddress parameter sets the baseline URL for the graphical resources used in the  HTML page.

The member variable m_strBaseAddress contains this parameter. In the sample application, this value is set, in the dialog constructor, to _T("c:\\dlgDHTMLEvents\\res"). Please modify according to your path.

Before a pointer to IPersistStreamInit can be obtained, Mshtml.dll has to be loaded (MSHTML is the IE rendering engine and parser for HTML). For this reason, the initial navigation of the browser is set to the valid  "about:blank" URL. LoadHTMLPage() is called from the event handler OnDocumentComplete(), provided m_bolLoaded is false.

The member function ExtractXMLInfo(CString strXML) converts the string parameter strXML, received from the Web browser control, to a valid xml MSXML2::IXMLDOMDocument* pxmlDoc object. To obtain a valid pointer to this interface, CoCreateInstance() is called as follows:

hr = CoCreateInstance( MSXML2::CLSID_DOMDocument, 
                       NULL, 
                       CLSCTX_INPROC_SERVER, 
                       MSXML2::IID_IXMLDOMDocument, 
                       (void**)&pxmlDoc);

After obtaining this pointer, the parameter strXML, which has the form _T("<element idevent='001'>value</element>"), is loaded and navigated to obtain the attribute node MSXML2::IXMLDOMNode* pattrNode, and the value node MSXML2::IXMLDOMNode* pNode. The event id and its associated value, are passed as parameters to the event handler function EventHandler(INT nEvent, CString strValue). The static controls m_stcEvent and m_stcValue display in the dialog, the DHTML event description and the associated value.

In summary, the steps involved for intercepting and handling HTML events are:

  1. Declare any desired event handlers in the HTML script.
  2. In each event handler, set the location.href property to the xml string that contains the values to be passed to the MFC host application.     
  3. Call the function that loads the HTML document stream from the event handler OnDocumentComplete().
  4. Implement OnBeforeNavigate2().
  5. Extract HTML element event information from the received xml string.
  6. Use this information in the MFC event handler function.

With minor modifications, these steps can be used for applications that utilizes CHtmlView classes.

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

Share

About the Author

Leopoldo Peralta
Colombia Colombia
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Generalgreate Pin
shaosjm18-Jan-10 3:19
membershaosjm18-Jan-10 3:19 
QuestionFails CWebBrowser2: Create fails Pin
lmeller33-Mar-09 11:23
memberlmeller33-Mar-09 11:23 
AnswerRe: Fails CWebBrowser2: Create fails Pin
chaitanyasingh8-Dec-10 23:53
memberchaitanyasingh8-Dec-10 23:53 
GeneralRe: Fails CWebBrowser2: Create fails Pin
hugwind12-Apr-11 5:13
memberhugwind12-Apr-11 5:13 
Questioncan update to ajax mode? Pin
nieoding3-Sep-08 23:32
membernieoding3-Sep-08 23:32 
AnswerRe: can update to ajax mode? Pin
BadJerry9-Nov-10 8:38
memberBadJerry9-Nov-10 8:38 
QuestionHow to get the html button event in win32 Pin
Member 462021615-May-08 1:16
memberMember 462021615-May-08 1:16 
AnswerRe: How to get the html button event in win32 Pin
nieoding3-Sep-08 23:29
membernieoding3-Sep-08 23:29 
QuestionEvent passing from bowser ctrl to MFC App using XML, XSL Pin
Sharad Goyal30-Oct-07 2:59
memberSharad Goyal30-Oct-07 2:59 
Questionhow to know when the document completly loaded in browser helper object Pin
krishnamaneni21-Aug-07 6:23
memberkrishnamaneni21-Aug-07 6:23 
Questionwhen I transfer this program into unicode, and display in the web browser ,there will be a useless line at the head of the picture, how should i deal with these situation? Pin
sude5-Nov-06 22:52
membersude5-Nov-06 22:52 
Questionwhen I transfer this program into unicode, and display in the web browser ,there will be a useless line at the head of the picture, how should i deal with these situation? Pin
sude5-Nov-06 22:51
membersude5-Nov-06 22:51 
Questionwhen I transfer this program into unicode, and display in the web browser ,there will be a useless line at the head of the picture, how should i deal with these situation? Pin
sude5-Nov-06 22:49
membersude5-Nov-06 22:49 
GeneralExcellent!! But some errors about UNICODE and Resource.. Pin
Naramalsami30-Nov-04 21:19
sussNaramalsami30-Nov-04 21:19 
GeneralNeed help!! Is there any way to find result code after CDHtmlDialog's Navigate method? ThanX Pin
dimak19-Apr-04 2:48
memberdimak19-Apr-04 2:48 
QuestionHow to programmaticaly click the Drop-down list to expand the list Pin
Khondker Ashif22-Dec-03 17:48
sussKhondker Ashif22-Dec-03 17:48 
Questionhow to navigate to html page from resources? Pin
george ivanov18-Dec-03 4:31
membergeorge ivanov18-Dec-03 4:31 
AnswerRe: how to navigate to html page from resources? Pin
SMadden26-Apr-07 12:46
memberSMadden26-Apr-07 12:46 
GeneralHelp needed in executing Javascript from a html page Pin
shivsun10-Oct-03 2:38
membershivsun10-Oct-03 2:38 
General? for web browser control Pin
george ivanov18-Dec-03 4:33
membergeorge ivanov18-Dec-03 4:33 
GeneralRe: Help needed in executing Javascript from a html page Pin
daniel vittori3-Feb-05 23:14
memberdaniel vittori3-Feb-05 23:14 
GeneralNeed help regarding parsing form input elements Pin
shivsun2-Jun-03 2:44
membershivsun2-Jun-03 2:44 
Questionhow to programatically click a button or link? Pin
noil_sg12-Jan-03 21:28
membernoil_sg12-Jan-03 21:28 
AnswerRe: how to programatically click a button or link? Pin
Leopoldo Peralta31-Jan-03 18:43
memberLeopoldo Peralta31-Jan-03 18:43 
GeneralHelp plz????????? Pin
xxhimanshu5-Aug-03 23:01
memberxxhimanshu5-Aug-03 23:01 
QuestionProgramitacally change font size to +2? Pin
Codin' Carlos1-Oct-02 11:33
memberCodin' Carlos1-Oct-02 11:33 
AnswerRe: Programitacally change font size to +2? Pin
Leopoldo Peralta5-Oct-02 4:44
memberLeopoldo Peralta5-Oct-02 4:44 
Generalgreat!! Pin
Anonymous23-Aug-02 3:34
sussAnonymous23-Aug-02 3:34 
GeneralExcellent, just a question using it on PropertySheet Pin
Davide Zaccanti14-Jan-02 20:11
memberDavide Zaccanti14-Jan-02 20:11 
GeneralRe: Excellent, just a question using it on PropertySheet Pin
Leopoldo Peralta16-Jan-02 17:34
memberLeopoldo Peralta16-Jan-02 17:34 
GeneralRe: Excellent, just a question using it on PropertySheet Pin
zacanti Davide16-Jan-02 19:21
memberzacanti Davide16-Jan-02 19:21 
GeneralRe: Excellent, just a question using it on PropertySheet Pin
Leopoldo Peralta17-Jan-02 17:20
memberLeopoldo Peralta17-Jan-02 17:20 
GeneralRe: Excellent, just a question using it on PropertySheet Pin
Davide Zaccanti17-Jan-02 20:21
memberDavide Zaccanti17-Jan-02 20:21 
GeneralRe: Excellent, just a question using it on PropertySheet Pin
ciroE3-Oct-06 4:42
memberciroE3-Oct-06 4:42 
GeneralMFC 7.0 Supports CDhtmlDialog Pin
Norm Almond14-Jan-02 3:11
memberNorm Almond14-Jan-02 3:11 
GeneralWow! Pin
Shog913-Jan-02 14:12
memberShog913-Jan-02 14:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160927.1 | Last Updated 13 Jan 2002
Article Copyright 2002 by Leopoldo Peralta
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid