Use cwebbrowser2 to obtain the ihtmldocument2 interface. The ihtmldocument2 interface is one of the most important interfaces in mshtml. After obtaining this interface, you can start to analyze the HTML code.
The following code retrieves a specific HTML text tag
Code
// Obtain the tag strtagname from the selected area of the current HTML document in ctlbrowser and store it in * ppelement
Bool getcrnthtmlelement (cwebbrowser2 & ctlbrowser, const cstring & strtagname, ihtmlelement ** ppelement)
{
* Ppelement = NULL; // initial as null
Cstring strtext;
Ccombstr cbstext, cbstagname;
Ccomptr <ihtmltxtrange> sptxtrange = NULL;
Static cstring selecttion_type_text = _ T ("text ");
Static cstring selecttion_type_control = _ T ("control ");
Static cstring selecttion_type_none = _ T ("NONE ");
Try
{
// Calculate the first control based on the user selection
Hresult hR = e_fail;
Ccomptr <idispatch> spdispdoc = ctlbrowser. get_document ();
Ccomptr <ihtmldocument2> sphtmldoc = NULL;
HR = spdispdoc-> QueryInterface (iid_ihtmldocument2, (void **) & sphtmldoc );
If (failed (HR) | null = sphtmldoc)
{
Return false;
}
Ccomptr <ihtmlselectionobject> spselection = NULL;
HR = sphtmldoc-> get_selection (& spselection );
If (succeeded (HR) & spselection)
{
HR = spselection-> get_type (& cbstext );
Strtext = cbstext;
If (0 = strtext. comparenocase (selecttion_type_text)
| 0 = strtext. comparenocase (selecttion_type_none ))
{
Ccomptr <idispatch> sptextrangedisp = NULL;
HR = spselection-> createRange (& sptextrangedisp );
If (succeeded (HR) & sptextrangedisp)
{
HR = sptextrangedisp-> QueryInterface (iid_ihtmltxtrange, (void **) & sptxtrange );
If (succeeded (HR) & sptxtrange) // get a text range here
{
Ccomptr <ihtmlelement> spelement = NULL;
// Get self element first for Tag: such as "H6"
HR = sptxtrange-> QueryInterface (iid_ihtmlelement, (void **) & spelement );
If (succeeded (HR) & spelement)
{
HR = spelement-> get_tagname (& cbstagname );
If (succeeded (HR) & 0 = strtagname. comparenocase (cstring (cbstagname )))
{// Found tag now
Return true;
}
}
// Loop search in parent for Tag: such as "H6"
Spelement = NULL;
Ccomptr <ihtmlelement> spparent = NULL;
HR = sptxtrange-> parentelement (& spparent );
While (succeeded (HR) & spparent)
{
HR = spparent-> get_tagname (& cbstagname );
If (succeeded (HR) & 0 = strtagname. comparenocase (cstring (cbstagname )))
{// Found tag now
Return true;
}
Spelement = spparent;
Spparent = NULL;
HR = spelement-> get_parentelement (& spparent );
}
}
}
}
}
}
Catch (cexception * E)
{
E-> reporterror ();
E-> Delete ();
}
Return false;
}