WPF WebBrowser控件与WinForms的比较

5

我正在创建一个WPF应用程序,其中使用了WebBrowser控件。有时需要查找HTML元素、调用点击事件以及其他基本功能。

在WinForms WebBrowser控件中,我可以通过以下方式实现:

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

在WPF WebBrowser控件中,我通过以下方式实现了相同的功能:
  dynamic d = webBrowser1.Document;  
  var el = d.GetElementById("someId").SetAttribute("value", "I change the value");

我也成功地使用动态类型在WPF WebBrowser控件中调用了单击事件。但有时会出现异常。

如何在WPF WebBrowser控件中查找HTML元素、设置属性和触发单击事件,而不必使用动态类型,因为我经常会遇到异常?我想用WPF WebBrowser控件替换我的WPF应用程序中的WinForms WebBrowser控件。


1
Winforms的HtmlDocument和HtmlElement包装类很好用。但是当DOM不包含你所希望的元素或属性时,它也会像炸弹一样失败。为了避免这种情况,它们也需要显式地检查null。 - Hans Passant
我确信该文档包含我正在寻找的HTML元素,因为我创建了该HTML文档进行测试。但是没错,我同意我将始终检查空异常... - Tono Nam
2个回答

1
使用以下命名空间,这样您就可以访问所有元素属性和事件处理程序属性:
    using mshtml;

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

在构造函数或XAML中设置您的LoadComplete事件:
    webBrowser.LoadCompleted += webBrowser_LoadCompleted;

然后在该方法中创建您的新Web浏览器文档对象并查看可用属性,并按以下方式创建新事件:

    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
    }

-3

我做这个的方法是...

使用HTTPRequest下载要呈现的页面的HTML文本。使用HTML Agility Pack注入JavaScript到HTML文本中。如果你想使用jQuery,那么你必须先将你的页面转换为jQuery格式,然后再绑定事件到你的DOM元素上。你也可以从脚本中调用你的C#函数,反之亦然。 没有动态类型的麻烦,因此也没有异常。

你还可以使用这个链接上的扩展方法来抑制WC中的脚本错误。

这个这个可能会有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接