其他分享
首页 > 其他分享> > 获取webbrowser中元素的屏幕坐标

获取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;

标签:tempEl,Point,Top,pos,webbrowser,坐标,OffsetRectangle,屏幕,Left
来源: https://www.cnblogs.com/soundcode/p/12512638.html