无法转换类型为' mshtml.HTMLDocumentClass'的COM对象界面类型' mshtml.DispHTMLDocument'

时间:2016-07-16 02:24:35

标签: c# html internet-explorer dom ui-automation

我无法从SHDOCvw.Internetexplorer即对象访问IE元素。以下是我的代码。

 //Manipulating HTML element

            HTMLDocument document = (HTMLDocument)ie.Document;    

            Console.WriteLine("Setting text box to google search text box");
            IHTMLElement element = document.getElementById("lst-ib");

有什么建议吗?我得到的错误是

  '((mshtml.HTMLDocumentClass)(document)).activeElement' threw an exception of type 'System.InvalidCastException'

尝试以下但得到同样的错误。

IHTMLDocument2 d = (IHTMLDocument2)ie.Document;

完整的代码在这里:

            SHDocVw.InternetExplorer ie = null;
            Console.WriteLine("\nLaunching an instance of IE");
            Process p = Process.Start("iexplore.exe", www.google.com);
            if (p == null)
            throw new Exception("Could not launch IE");
            Console.WriteLine("Process handle = " + p.MainWindowHandle.ToString());
            SHDocVw.ShellWindows allBrowsers = new SHDocVw.ShellWindows();
            Console.WriteLine("Number active browsers = " + allBrowsers.Count);
            if (allBrowsers.Count == 0)
            throw new Exception("Cannot find IE");
            Console.WriteLine("Attaching to IE");
            int i = 0;
            while (i < allBrowsers.Count && ie == null)
            {
            InternetExplorer e = (InternetExplorer)allBrowsers.Item(i);
            if (e.HWND == (int)p.MainWindowHandle)
            ie = e;
            ++i;
            }
            if (ie == null)
            throw new Exception("Failed to attach to IE");
             HTMLDocument document = (HTMLDocument)ie.Document;               
             IHTMLDocument2 d = (IHTMLDocument2)ie.Document;

             Console.WriteLine("Setting text box to google search text box");
             IHTMLElement element = document.getElementById("lst-ib");
             The above line is the one which throws the error:
            "Unable to cast COM object of type 'mshtml.HTMLDocumentClass' to interface type 'mshtml.DispHTMLDocument'"

0 个答案:

没有答案