2012-01-15 130 views
5

我正在创建一个wpf应用程序,我正在使用webbrowser控件。反正有时我需要寻找html元素,调用点击和其他基本功能。WPF浏览器控件vs winforms

在的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控件中单击。有时我会得到豁免。

我如何能够寻找HTML元素,设置属性和调用点击在WPF WebBrowser控件,而无需使用动态类型的,我经常收到异常?我想用wpf webbrowser控件替换我的wpf应用程序中的winforms webbrowser控件。

+1

Winforms HtmlDocument和HtmlElement包装类很好。但是,当DOM不包含你希望的元素或属性时,它就会大声地轰炸。他们也要求你明确检查空值以避免炸弹。 – 2012-01-15 16:15:05

+0

我确定该文档包含我正在寻找的html元素,因为我为测试目的创建了html文档。但是,我同意我会一直检查零豁免... – 2012-01-15 16:21:07

回答

-3

我这样做是这样的...

页面下载HTML文本,你想用的HTTPRequest渲染。使用HTML文本中的HTML敏捷包注入Java脚本。如果你想使用jQuery,那么你必须首先jQuerify你的页面,然后绑定事件与你的DOM元素。你也可以在脚本中调用你的c#函数和其他方法。 没有搞乱动态类型,因此也没有例外。

您还可以使用扩展方法在此link上禁用WC中的脚本错误。

Thisthis可能会有所帮助。

1

使用下面的命名空间的方式,你可以得到所有的元素属性和事件处理性能:

using mshtml; 

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

在构造函数或XAML中设置您的LoadComplete事件:

webBrowser.LoadCompleted += webBrowser_LoadCompleted; 

然后在方法创建新的浏览器文档对象并查看可用属性并创建新事件,如下所示:

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 
    }