第一次加载后使用 getElementById 出现异常 0x800A01B6

Exception 0x800A01B6 using getElementById after the first load

我用 visual studio XML 功能区为 Powerpoint 创建了一个功能区。此功能区有一个按钮,简化后,可以执行以下操作:

我第一次单击功能区按钮时它工作正常,但在我单击该按钮后,它会引发异常 0x800A01B6。

这是我点击按钮时执行的代码:

Dim oType As Type = Type.GetTypeFromProgID("InternetExplorer.Application")
If oType IsNot Nothing Then
    Dim ie As SHDocVw.InternetExplorer
    ie = Nothing
    ie = TryCast(Activator.CreateInstance(oType), SHDocVw.InternetExplorer)

    If ie IsNot Nothing Then
        Dim oEmpty As Object = [String].Empty
        Dim oURL As Object = targetURL
        ie.AddressBar = False
        ie.MenuBar = False
        ie.ToolBar = 0
        ie.Visible = True
        ie.Height = 800
        ie.Width = 1100
        ie.Navigate(oURL, oEmpty, oEmpty, oEmpty, oEmpty)
    End If

    Do While (ie.Busy Or ie.ReadyState <> READYSTATE.READYSTATE_COMPLETE)
        Sleep(1000)
        Application.DoEvents()
    Loop

        Sleep(10000) ' 10 seconds for testing purpose

    Dim str As String = String.Empty
    Dim hdnstring As HTMLInputElement = ie.Document.getElementById("hdnstring")
    str = hdnstring.value

    DoSomething(str)

    ie.Quit()
    ie = Nothing
End If

这是打开网站的代码 (targetURL),代码在每次加载时都保持不变,只有隐藏值发生变化:

<html>
<body>
    <form name="form1" id="form1">
        <input type="hidden" name="hdnstring" id="hdnstring" value="Get This String" />
    </form>
</body>
</html>

我第二次(及之后)执行该功能:IE 打开,网站完全加载,等待 10 秒,然后我在行中收到错误:

Dim hdnstring As HTMLInputElement = ie.Document.getElementById("hdnstring")

出现异常 0x800A01B6 消息。

最奇怪的是,如果我在 IE 上下文菜单中单击 viewsource 时有 10 秒的延迟(用于测试目的),每次单击按钮时它都完美无缺;但如果我不这样做,则会出现异常 0x800A01B6。

知道我做错了什么吗?

错误详情图片:

Document 属性 的类型仅在 运行 时才解析,因此在此之前它是 Object。这就是为什么调用其中的任何方法会导致所谓的后期绑定——您还不知道 getElementById 方法是否存在,因此必须在 运行 时间内确定。

您很可能会收到错误,因为 Document 不是 IHTMLDocument3 type,这是唯一包含 getElementById 方法的文档类型。

您可以尝试将 Document 转换为 IHTMLDocument3 接口。由于它继承了 IHTMLDocumentIHTMLDocument2,即使文档实际上是较早的类型之一,您也可以在它们之间进行转换。

DirectCast(ie.Document, IHTMLDocument3).getElementById("hdnstring")