Internet Explorer 晚期绑定自动化
使用晚绑定技术的Internet Explorer自动化示例代码,无需依赖Microsoft.mshtml和shdocvw。
引言
大多数开发人员通常需要Internet Explorer自动化,这基本上意味着打开浏览器,填写一些表单,并通过编程方式发布数据。
最常见的方法是使用shdocvw.dll (Microsoft Web浏览器控件) 和Mshtml.dll (HTML解析和渲染组件),或者Microsoft.Mshtml.dll,它实际上是Mshtml.dll的.NET包装器。您可以在这里获取有关Internet Explorer - 关于浏览器的更多信息。
如果您选择上述方法和DLL,让我们看看您可能需要处理的一些问题
- 您必须分发这些DLL,因为您的项目将依赖于这些DLL,如果无法正确部署它们,这将是一个严重的问题。只需搜索一下关于shdocvw 和mshtml.dll 分发问题的相关内容,您就会明白我在说什么了。
- 您必须部署一个8 MB的Microsoft.mshtml.dll,因为此DLL不是.NET框架的一部分。
在这种情况下,我们需要做的是使用晚绑定技术。为上述DLL编写我们自己的包装器。当然,我们这样做比使用这些DLL更有用。例如,我们不需要检查文档下载操作是否完成,因为IEHelper
会为我们完成。
背景
我们在这里需要做的是使用晚绑定技术,这篇文章已经成功地解释了。感谢Ariadne提供了这篇精彩的文章。
对我来说,这里缺失的一点是附加到COM事件,我们确实需要知道这些事件来查询文档下载操作是否完成。
以下是我们如何连接到Web浏览器的事件
private IConnectionPointContainer connectionPointContainer;
private IConnectionPoint connectionPoint;
private int pdwCookie = 0;
private void registerDocumentEvents()
{
connectionPointContainer = IeApplication as IConnectionPointContainer;
Guid guid = new Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D");
connectionPointContainer.FindConnectionPoint(ref guid, out connectionPoint);
browserEvents = new DWebBrowserEvents2_Helper();
connectionPoint.Advise(browserEvents, out pdwCookie);
DocumentStatus ds = DocumentStatus.Instance;
ds.DownloadComplete = false;
}
在我们附加到Web浏览器事件之后,我们需要使用一个单例类来查询文档状态。这就是DocumentStatus
所做的。
在从DocumentComplete
事件获得反馈后,我们将DownloadComplete
设置为true
,以便我们的代码可以继续运行。
void DWebBrowserEvents2.DocumentComplete(object pDisp, ref object URL)
{
DocumentStatus ds = DocumentStatus.Instance;
ds.DownloadComplete = true;
}
当然,当完成时,我们需要注销事件...
private void unregisteDocumentEvents()
{
connectionPoint.Unadvise(pdwCookie);
Marshal.ReleaseComObject(connectionPoint);
}
如果您想知道我是如何编写这些COM包装器的,让我给您一个提示:使用由aurigma提供的Comto.net。
使用代码
只需启动一个新的IEHelper
实例。导航到您想要访问的页面。通过名称或ID找到一些输入元素。设置它们的值并提交。
IEHelper ie = new IEHelper();
ie.OpenAVisibleBlankDocument();
object p = null;
string url = @"http://mail.google.com/mail/?hl=en&tab=wm";
bool ret = ie.Navigate(url, ref p, ref p, ref p, ref p);
ie.SetValueById("Email", txtUserName.Text);
ie.SetValueById("Passwd", txtPassword.Text);
ie.ClickButtonByName("signIn");
接下来做什么
您需要做的是填写空白。因为当您下载源代码时,您会看到大多数事件尚未实现。如果您认为您需要这些事件,请根据您的要求对其进行改进。
void DWebBrowserEvents2.OnQuit()
{
throw new Exception("The method or operation is not implemented.");
}