2013-04-05 15 views
3

我加Microsoft.mshtml爲我的項目的引用,遠遠傳來這樣的:如何獲取WPF中瀏覽器控件的輸入框的值?

 mshtml.IHTMLDocument2 document = (mshtml.IHTMLDocument2)webbrowser.Document; 
     string username = document.all["username"].GetAttribute("value"); 

但二號線不起作用。它說

「錯誤CS0021:無法與應用[]索引到 類型的 'mshtml.IHTMLElementCollection' 表達式」

懸停在 「所有」 的時候。我如何訪問所有元素?

回答

4

試試這個:

var document = (IHTMLDocument3) webbrowser.Document; 
var value = 
    document.getElementsByName("username") 
      .OfType<IHTMLElement>() 
      .Select(element => element.getAttribute("value")) 
      .FirstOrDefault(); 
+0

它的工作原理。我可以問一下嗎? getElementsByName的結果被包裝成可以執行LINQ查詢的東西,然後使用IHTMLElement類型來過濾結果,然後只選擇Attribute屬性,然後獲取第一個結果?這是正確的還是這也是一些COM IHTMLDocument3功能?是否有可能與document.all做到這一點,或者有沒有理由不會在c#中工作或不方便? – marc40000 2013-04-05 14:39:09

+0

方法'getElementsByName'返回'IHTMLElementCollection',它實現'IEnumerable'接口,所以我們可以使用LINQ遍歷它。爲此,我們應該安全地將每個元素轉換爲IHTMLElement。 'document.all'也返回'IHTMLElementCollection',這意味着你可以像上面的方法一樣處理它。 – SHSE 2013-04-05 15:16:15

0

掙扎了幾個小時,這個解決方案爲我工作後。

Dim document = DirectCast(MainBrowser.Document, IHTMLDocument3) 
Dim formName = document.getElementsByName(AppSettings("myFormName")).OfType(Of IHTMLElement)().Select(Function(element) element.getAttribute("name")).FirstOrDefault() 
相關問題