WPF webbrowser control vs winforms

2020-03-24 04:23发布

问题:

I am creating a wpf application where I am using a webbrowser control. anyways sometimes I am required to look for html elements, invoke clicks, and other basic functionality.

In winforms webbrowser control I am able to achieve this by doing:

 webBrowser1.Document.GetElementById("someId").SetAttribute("value", "I change the value");

In wpf webbrowser control I managed to achieve the same thing by doing:

  dynamic d = webBrowser1.Document;  
  var el = d.GetElementById("someId").SetAttribute("value", "I change the value");

I also managed to invoke a click in the wpf webbrowser control by using the dynamic type. Sometimes I get exeptions though.

How will I be able to look for html elements, set attributes and invoke clicks in a wpf webbrowser control without having to use dynamic types where I often get exceptions? I will like to replace my winforms webbrowser control in my wpf application by a wpf webbrowser control.

回答1:

The way I have done this is...

Download HTML text of the page you want to render using HTTPRequest. Inject java script using HTML agility pack in HTML text. If you want to use jQuery then you have to jQuerify your page first and then bind event with your dom elements. You can also call your c# function from within the script and other way around. No messing around with dynamic types and hence no exception.

You can also suppress script error in your WC using extension method on this link.

This and this may help.



回答2:

Use the following namespace that way you can get to all element properties and eventhandler properties:

    using mshtml;

    private mshtml.HTMLDocumentEvents2_Event documentEvents;
    private mshtml.IHTMLDocument2 documentText;

in constructor or xaml set your LoadComplete event:

    webBrowser.LoadCompleted += webBrowser_LoadCompleted;

then in that method create your new webbrowser document object and view the available properties and create new events as follows:

    private void webBrowser_LoadCompleted(object sender, NavigationEventArgs e)
    {
        documentText = (IHTMLDocument2)webBrowserChat.Document; //this will access the document properties as needed
        documentEvents = (HTMLDocumentEvents2_Event)webBrowserChat.Document; // this will access the events properties as needed
        documentEvents.onkeydown += webBrowserChat_MouseDown;
        documentEvents.oncontextmenu += webBrowserChat_ContextMenuOpening;
    }

    private void webBrowser_MouseDown(IHTMLEventObj pEvtObj)
    {
         pEvtObj.returnValue = false; // Stops key down
         pEvtObj.returnValue = true; // Return value as pressed to be true;
    }

    private bool webBrowserChat_ContextMenuOpening(IHTMLEventObj pEvtObj)
    {
        return false; // ContextMenu wont open
        // return true;  ContextMenu will open
        // Here you can create your custom contextmenu or whatever you want
    }