Inspect element from my WPF WebBrowser, using “inspect element(s)”(IE,Chrome,Firefox) to get the css path(“copy css-path”)

与世无争的帅哥 提交于 2019-12-02 02:43:14
user254197

Ok,I found a solution including the winform webbrowser into my wpf application(take a look at my question regarding, processes and resources):

1.The .xaml part(namespace)(more details):

xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

2.The .xaml part(WebBrowser)(more details):

<WindowsFormsHost Name="wfhSample" Margin="372,12,12,205" Loaded="wfhSample_Loaded">
    <WindowsFormsHost.Child>
        <wf:WebBrowser />
    </WindowsFormsHost.Child>
</WindowsFormsHost>

3.The code behind file(more details):

   private void wfhSample_Loaded(object sender, RoutedEventArgs e)
    {
        bool complete = false;
        (wfhSample.Child as System.Windows.Forms.WebBrowser).DocumentCompleted += delegate
        {
            if (complete)
                return;
            complete = true;
            // DocumentCompleted is fired before window.onload and body.onload
            (wfhSample.Child as System.Windows.Forms.WebBrowser).Document.Window.AttachEventHandler("onload", delegate
            {
                // Defer this to make sure all possible onload event handlers got fired
                System.Threading.SynchronizationContext.Current.Post(delegate
                {
                    // try webBrowser1.Document.GetElementById("id") here
                    //System.Windows.MessageBox.Show("window.onload was fired, can access DOM!");
                    var bla = (wfhSample.Child as System.Windows.Forms.WebBrowser).Document.DomDocument;
                    HTMLDocumentEvents2_Event _docEvent = (HTMLDocumentEvents2_Event)(wfhSample.Child as System.Windows.Forms.WebBrowser).Document.DomDocument;
                    _docEvent.onclick += new HTMLDocumentEvents2_onclickEventHandler(OldClickEventHandler);
                }, null);
            });
        };

        (wfhSample.Child as System.Windows.Forms.WebBrowser).Navigate("http://www.example.com");
    }
    private bool OldClickEventHandler(mshtml.IHTMLEventObj e)
    {
        System.Drawing.Point point = System.Windows.Forms.Control.MousePosition;
        System.Drawing.Point refPoint = (wfhSample.Child as System.Windows.Forms.WebBrowser).PointToClient(new System.Drawing.Point(point.X, point.Y));
        System.Windows.Forms.HtmlElement refHtmlElement = (wfhSample.Child as System.Windows.Forms.WebBrowser).Document.GetElementFromPoint(refPoint);
        var restult = refHtmlElement.TagName; 
        return true;
    }

4.To get the full CSS-Path or XPath you could use Fizzler, HTMLAgilityPack(this).

Sometimes it is a little buggy(resizing window, changing tabs), the event handler does not fire anymore.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!