获取webbrowser中元素的屏幕坐标

/// <summary>
        /// 获取webbrowser中html元素的屏幕坐标
        /// </summary>
        /// <param name="webBrowser"></param>
        /// <param name="htmlElem"></param>
        /// <returns></returns>
        public Point GetHtmlElementClientPoint(WebBrowser webBrowser, HtmlElement htmlElement)
        {
            Point p = GetOffset(htmlElement);

            HTMLDocument doc = webBrowser.Document.DomDocument as HTMLDocument;

            int sl = int.Parse(doc.documentElement.getAttribute("ScrollLeft").ToString());
            int st = int.Parse(doc.documentElement.getAttribute("ScrollTop").ToString());

            //加上窗体的位置及控件的位置及窗体边框,50和8是窗体边框,不同的元素宽高不一样,需要可适当调整
            p.X += htmlElement.OffsetRectangle.Left + this.Left + webBrowser1.Left + 8 - sl;
            p.Y += htmlElement.OffsetRectangle.Top + this.Top + webBrowser1.Top + 50 - st;
            return p;
        }

        private Point GetOffset(HtmlElement el)
        {
            //get element pos
            Point pos = new Point(el.OffsetRectangle.Left, el.OffsetRectangle.Top);

            //get the parents pos
            HtmlElement tempEl = el.OffsetParent;
            while (tempEl != null)
            {
                pos.X += tempEl.OffsetRectangle.Left;
                pos.Y += tempEl.OffsetRectangle.Top;
                tempEl = tempEl.OffsetParent;
            }
            return pos;
        }

//调用
HtmlElement txtCodeHE = htmlDoc.GetElementById("txtCode");
Point txtCodeHEClientPoint = GetHtmlElementClientPoint(webBrowser1, txtCodeHE);
Cursor.Position = txtCodeHEClientPoint;
上一篇:c# winform 打开html界面(含引用外部文件js)


下一篇:Delphi让网页只允许在WebBrowser里面打开