public static void SpawnIEWithSource(String szSourceHTML)
{
OleVariant ie; //IWebBrowser2
OleVariant ie = new InternetExplorer();
ie.Navigate2("about:blank");
OleVariant webDocument = ie.Document;
webDocument.Write(szSourceHTML);
webDocument.close;
ie.Visible = True;
}
现在开始尝试从托管代码与COM进行交互的漫长而痛苦的过程。
PInvoke.net已经包含了IWebBrower2 translation,其中相关部分如下:
[ComImport,
DefaultMember("Name"),
Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
SuppressUnmanagedCodeSecurity]
public interface IWebBrowser2
{
[DispId(500)]
void Navigate2([In] ref object URL, [In] ref object Flags, [In] ref object TargetFrameName, [In] ref object PostData, [In] ref object Headers);
object Document { [return: MarshalAs(UnmanagedType.IDispatch)] [DispId(0xcb)] get; }
}
我已经创建了COM类:
[ComImport]
[Guid("0002DF01-0000-0000-C000-000000000046")]
public class InternetExplorer
{
}
现在是我实际进行 C# 事务的时候了:
public static void SpawnIEWithSource(String szHtml)
{
PInvoke.ShellDocView.IWebBrowser2 ie;
ie = (PInvoke.ShellDocView.IWebBrowser2)new PInvoke.ShellDocView.InternetExplorer();
//Navigate to about:blank to initialize the browser
object o = System.Reflection.Missing.Value;
String url = @"about:blank";
ie.Navigate2(ref url, ref o, ref o, ref o, ref o);
//stuff contents into the document
object webDocument = ie.Document;
//webDocument.Write(szHtml);
//webDocument.Close();
ie.Visible = true;
}
细心的读者会注意到,IWebBrowser2.Document是一个后期绑定的IDispatch。我们使用的是Visual Studio 2005,在我们和客户的机器上都安装了.NET 2.0。
那么,在仅支持后期绑定IDispatch的对象上调用方法的.NET 2.0方法是什么呢?
在Stack Overflow上快速搜索使用C#从IDispatch中调用方法,this post说我想要的在.NET中不可能实现。
那么,从C# .NET 2.0中是否可以使用COM呢?
问题在于有一个被接受的设计模式,我想在C#/.NET中使用它。它涉及到启动Internet Explorer进程,并给它HTML内容,同时不使用临时文件。
一个被拒绝的设计想法是在WinForm上托管Internet Explorer。
一个可接受的替代方案是启动系统注册的Web浏览器,给它要显示的HTML,而不使用临时文件。
绊脚石是在.NET世界中继续使用COM对象。具体问题涉及在不需要C# 4.0的情况下执行对IDispatch的后期绑定调用。(即在使用.NET 2.0时)