0

I can see this being a simple correction however it has me stumped.

This is the error I am getting

COMException was unhandled

Error HRESULT E_FAIL has been returned from a call to a COM component.

This is the code (I have blanked out the URL however they are valid)

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;

    }

This is the line that is generating the error

IHTMLDocument2 HTMLDoc = (IHTMLDocument2)ie.Document;

The web page opens fine however when I try to assign the Document to the IHTMLDocument2 it fails.

Any help would be great

Chris Crew
  • 353
  • 4
  • 15

2 Answers2

5

You are forgetting to wait for the page load to be completed. The while (ie.Busy) ; loop is quite ugly, you don't want to burn 100% core while waiting for IE to complete. Use the DocumentComplete event instead. And a state machine to keep track of where you are. Something like this:

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);
}

Consider using the WebBrowser class so you don't have to run IE out-of-process. This answer shows you how to run it in a separate thread. Which is a very likely reason you got E_FAIL on your code.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

The code works locally for me but I will take a crack for you.

Take a look at the ie.Document type. For me it returns mshtml.HTMLDocumentClass which implements the IHTMLDocument2 interface. Perhaps you are not reference the appropriate DLLs. I assume you added SHDocVw.dll and mshtml references by hand?

Also, check your timings. I had the E_FAIL when casting the document but the Navigate was not complete. So you would need to wait before performing the cast.

Ken Brittain
  • 2,255
  • 17
  • 21