100分,webBrowser中,鼠标点击的坐标,不在点击html元素的Rectangle之中!
//下面是代码打开百度后鼠标点击查询按钮,发现鼠标点击的坐标,不在所点击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++;
if (het.TagName.ToUpper() == "HTML")
{
tag = 1;
}
}
//计算html元素的Rectangle的函数
private Rectangle GetAbsPos(HtmlElement em)
{
Rectangle rect = new Rectangle();
Point p = new Point();
p.X = 0;
p.Y = 0;
int wd = 0;
int ht = 0;
int i = 0;
while (em != null)
{
rect = em.OffsetRectangle;
if (i == 0)
{
wd = rect.Width;
ht = rect.Height;
i++;
}
p.X += rect.X - em.ScrollLeft;
p.Y += rect.Y - em.ScrollTop;
em = em.OffsetParent;
};
rect.X = p.X;
rect.Y = p.Y;
rect.Width = wd;
rect.Height = ht;
return rect;
}
[解决办法]
这个不清楚怎么搞
[解决办法]
高手来也。webBrowser这个取不到html控件在webBrowser中的绝对坐标的。要换成axWebBrowser才行。
然后
private Point GetInputLocation(string id)
{
HTMLDocument myDoc = (mshtml.HTMLDocument)axWebBrowser.Document;
HTMLInputElement tag = (HTMLInputElement)myDoc.getElementById(id);
return new Point(tag.getBoundingClientRect().left, tag.getBoundingClientRect().top);
}
如果你非得用WebBrowser还有一方法就是给网页注入JS代码,由js代码取getBoundingClientRect().left, tag.getBoundingClientRect().top后反回给C#
我知道楼主你想模拟点击百度连接或按钮。。。
[解决办法]
虽然对于坐标之类的很不敏感,而且要怎么计算坐标我也没有好的办法 . 不过看完楼主的代码发现有所体悟.
还有楼上所说的,如果 "楼主是想模拟点击百度连接或按钮" ,却有更好的不需要计算坐标的方式就能实现的.