簡體   English   中英

嘗試使用SHDocVw.InternetExplorer.Document訪問DOM時出錯

[英]Error when trying to access DOM using SHDocVw.InternetExplorer.Document

我可以看到這是一個簡單的更正,但是它讓我感到困惑。

這是我得到的錯誤

COMException未處理

錯誤HRESULT E_FAIL已從對COM組件的調用返回。

這是代碼(我將網址空白了,但是它們是有效的)

class SMSHandler
{
    private InternetExplorer ie;
    private object URL = "##########";
    private object URL2 = "###########";

    public SMSHandler()
    {
        ie = new InternetExplorer();
        ie.Visible = true;
    }

    public void openMACS()
    {
        object Empty = 0;

        ie.Navigate2(ref URL, ref Empty, ref Empty, ref Empty, ref Empty);

        while (ie.Busy);

        ie.Navigate2(ref URL2, ref Empty, ref Empty, ref Empty, ref Empty);

        IHTMLDocument2 HTMLDoc = (IHTMLDocument2)ie.Document;

    }

這是產生錯誤的行

IHTMLDocument2 HTMLDoc = (IHTMLDocument2)ie.Document;

網頁打開正常,但是當我嘗試將文檔分配給IHTMLDocument2時,它失敗了。

任何幫助都會很棒

您忘記等待頁面加載完成。 一會兒(即忙); 循環非常丑陋,您不想在等待IE完成時消耗100%的內核。 請改用DocumentComplete事件。 還有狀態機來跟蹤您的位置。 像這樣:

private int state = 0;
public SMSHandler()
{
    ie = new InternetExplorer();
    ie.DocumentComplete += ie_DocumentComplete;
    ie.Visible = true;
}

void ie_DocumentComplete(object pDisp, ref object URL) {
    object Empty = 0;
    if (state == 1) {
        ie.Navigate2(ref URL2, ref Empty, ref Empty, ref Empty, ref Empty);
        state++;
    }
    else if (state == 2) {
        IHTMLDocument2 HTMLDoc = (IHTMLDocument2)ie.Document;
        // etc..
        state = 0;
    }
}

public void openMACS()
{
    object Empty = 0;
    state = 1;
    ie.Navigate2(ref URL, ref Empty, ref Empty, ref Empty, ref Empty);
}

考慮使用WebBrowser類,這樣您就不必在進程外運行IE。 此答案顯示了如何在單獨的線程中運行它。 這很可能是您的代碼中包含E_FAIL的原因。

該代碼對我來說本地有效,但我會為您解決。

看一下ie.Document類型。 對於我來說,返回mshtml.HTMLDocumentClass其實現IHTMLDocument2接口。 也許您沒有引用適當的DLL。 我假設您手動添加了SHDocVw.dllmshtml引用?

另外,檢查您的時間安排。 投射文檔時我遇到了E_FAIL ,但導航未完成。 因此,您需要等待執行轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM