//下面是代码打开百度后鼠标点击查询按钮,发现鼠标点击的坐标,不在所点击html元素的Rectangle之中!其他网页也有这个问题,具体问题已用红色字体标出,怎么样才能两个坐标一直呢
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("http://www.baidu.com");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.ReadyState == WebBrowserReadyState.Complete && webBrowser1.Document != null )
{
HtmlElementCollection hec = webBrowser1.Document.All;
foreach (HtmlElement hlet in hec)
{
hlet.Click += new HtmlElementEventHandler(HtmlElement_Click);
}
}
}
public int tag = 1;
private void HtmlElement_Click(Object sender, HtmlElementEventArgs e)
{
HtmlElement het = (HtmlElement)sender;
if (tag == 1)
{
//下面计算鼠标点击坐标的实际值,经测试是正确的坐标
IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2;
IHTMLElement2 element = document.body as IHTMLElement2;
int scrolltop = webBrowser1.Document.Body.ScrollTop - element.clientTop;
int scrollLeft = webBrowser1.Document.Body.ScrollLeft - element.clientLeft;
if (document.body.parentElement != null)
{
IHTMLElement2 parent = document.body.parentElement as IHTMLElement2;
scrolltop += parent.scrollTop - parent.clientTop;
scrollLeft += parent.scrollLeft - parent.clientLeft;
}
int positionX = e.ClientMousePosition.X + scrollLeft;
int positionY = e.ClientMousePosition.Y + scrolltop;
richTextBox1.Text += positionX.ToString() + "," + positionY.ToString() + "\r\n";//显示值
//下面计算所点击的HTML元素的坐标值有偏移,不正确,上面计算的坐标值不在下面的Rectangle之中
Rectangle rg = GetAbsPos(het);
richTextBox1.Text += rg.X.ToString() + "," + (rg.X + rg.Width).ToString() + "," + rg.Y.ToString() + "," + (rg.Y + rg.Height).ToString() + "\r\n---------------------\r\n";
}
tag++;