InternetExplorer 被设置为 __ComObject 而不是 SHDocVw.InternetExplorer
-
14-11-2019 - |
题
我在使用 SHDocVw.dll 中的 InternetExplorer 时遇到问题。我还引用了 mshtml.tlb(在谷歌搜索时,我确实读到了 1 条评论,说我应该引用 mshtml.dll,但这不能在 微软 Visual Studio Express, ,但我不知道这有多真实)。这是最基本形式的一个小函数,但对我来说不起作用:
public static HtmlElement GetDocumentControlByID(
ref SHDocVw.InternetExplorer IEObj,
string ControlID)
{
HtmlElement ReturnElement = IEObj.Document.GetElementById(ControlID);
return ReturnElement;
}
问题是,当我创建 IEObj 实例时,它被认为是类型 System.__ComObject
代替 SHDocVw.InternetExplorer
, ,并且所有子部分也是类型 System.__ComObject
. 。当我尝试以下任何陈述时......
Document WebDoc = IEObj.Document;
HtmlElement ReturnElement = IEObj.Document.GetElementById(ControlID);
...我不断收到相同的错误消息:
不能隐式将类型的“系统.__ comobject”转换为“ system.windows.forms.htmlelement”(显然,转换为类型是不同的
IEObj.Document
).
我是 C# 新手(来自 VBA,所以我熟悉编程),但在 VBA 中,等效项可以完美工作,无需以任何方式进行转换。
难道是我做错了什么?如果这是我创建的对象,以下是(大致)我用来测试该函数的代码:
public static void Main(String [] args)
{
SHDocVw.InternetExplorer IEObj = new SHDocVw.InternetExplorer();
IEObj.Navigate("http://sports.ladbrokes.com/");
while (IEObj.ReadyState != 4)
{
}
// There is a textbox that definitely exists
HtmlElement NetControl = GetDocumentControlByID(ref IEObj, "username");
// I was goint to manipulate it after this, but it crashes in the above function.
}
我真正想做的就是锁定各种元素,以便我可以在文本框中输入文本、单击按钮等。我还需要能够使用文档变量(例如 文档.Body.InnerHtml, , ETC)。整个项目是一堆包含在 DLL 中的函数,可供其他项目引用。
解决方案
您正在尝试使用 WinForms HtmlElement
类,其中 不是 一个 COM 对象。
你不能混合本地人 InternetExplorer
WinForms 中具有托管类的 COM 对象。
您应该使用 WinForms 类( WebBrowser
控制)代替。
在大多数情况下,您根本不需要 COM。