2012-01-15 59 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 
    }