【问题标题】:How to get the value of an input box of the webbrowser control in WPF?WPF中如何获取webbrowser控件输入框的值?
【发布时间】:2013-03-27 23:07:06
【问题描述】:

我添加了 Microsoft.mshtml 作为对我的项目的引用,并且走到了这一步:

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

但第二行不起作用。它说

“错误 CS0021:无法使用 [] 将索引应用于类型表达式 'mshtml.IHTMLElementCollection'"

当悬停在“全部”上时。如何访问所有元素?

【问题讨论】:

    标签: c# html wpf browser


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 它有效。请问真的可以吗? getElementsByName 的结果被包装到我可以执行 LINQ 查询的东西中,你用它来按类型 IHTMLElement 过滤结果,然后只选择值 Attribute 然后得到第一个结果?这是正确的还是这也是一些 COM IHTMLDocument3 功能?是否也可以使用 document.all 来做到这一点,或者是否有原因在 c# 中不起作用或不方便?
    • 方法 getElementsByName 返回实现 IEnumerable 接口的 IHTMLElementCollection,因此我们可以使用 LINQ 对其进行迭代。为此,我们应该安全地将每个元素转换为IHTMLElementdocument.all 也返回 IHTMLElementCollection 这意味着你可以像上面的方法一样处理它。
    【解决方案2】:

    经过几个小时的努力,这个解决方案对我有用。

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

    【讨论】:

      猜你喜欢
      • 2012-10-26
      • 2018-10-15
      • 1970-01-01
      • 2023-03-12
      • 2011-02-25
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多