Convert IHTMLDOMNode to IHTMLElement?
I would like to convert an IHTMLDOMNode
to IHTMLElement
in C#, I have tried the following:
IHTMLElement tempElement = node as IHTMLElement;
//node is a instance of IHTMLDOMNode internface
However, this did not work -- tempElement
is null
. Is there a way to perform this conversion correctly? Note that in my application, I try to use WebBrowser
to access every node in the DOM tree and get their coordinates.
here are my source code, could you tell me what should I do?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using mshtml;
namespace TestWindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.ScrollBarsEnabled = true;
webBrowser1.Url = new Uri("http://www.bing.com");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HTMLDocument document = (HTMLDocument)webBrowser1.Document.DomDocument;
IHTMLDOMNode bodyNode = (IHTMLDOMNode)webBrowser1.Document.Body.DomElement;
TranversalDOM(document, bodyNode);
}
private void TranversalDOM(HTMLDocument document, IHTMLDOMNode node)
{
if (node.nodeType == 3)
{
string nodeInfo = no开发者_JAVA百科de.nodeValue.ToString();
nodeInfo += ">>>";
IHTMLElement tempElement = node as IHTMLElement;
//how to convert IHTMLDOMNode to IHTMLElement?
int X1 = findPosX(tempElement);
int X2 = X1 + tempElement.offsetWidth;
int Y1 = findPosY(tempElement);
int Y2 = Y1 + tempElement.offsetHeight;
nodeInfo += " LeftTop: (";
nodeInfo += X1.ToString();
nodeInfo += ",";
nodeInfo += Y1.ToString();
nodeInfo += ")";
nodeInfo += " RightBottom: (";
nodeInfo += X2.ToString();
nodeInfo += ",";
nodeInfo += Y2.ToString();
nodeInfo += ")";
listBox1.Items.Add(nodeInfo);
}
else
{
IHTMLDOMChildrenCollection childNodes = node.childNodes as IHTMLDOMChildrenCollection;
foreach (IHTMLDOMNode n in childNodes)
{
TranversalDOM(document, n);
}
}
}
public int findPosX(IHTMLElement obj)
{
int curleft = 0;
if (obj.offsetParent != null)
{
while (obj.offsetParent != null)
{
curleft += obj.offsetLeft;
obj = obj.offsetParent;
}
}
return curleft;
}
public int findPosY(IHTMLElement obj)
{
int curtop = 0;
if (obj.offsetParent != null)
{
while (obj.offsetParent != null)
{
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
}
return curtop;
}
}
}
You cannot convert when it is not an IHTMLElement
.
I am not familiar with these interfaces but you might try:
IHTMLElement tempElement = (IHTMLElement)node;
精彩评论