【发布时间】:2010-10-02 22:59:58
【问题描述】:
在我上一个开发环境中,我能够轻松地与 COM 交互,调用 COM 对象上的方法。以下是原始代码,翻译成 C# 风格的代码(以掩盖原始语言):
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。
那么 .NET 2.0 调用对象上的方法的方法是什么,在某种程度上,它只支持后期绑定的 IDispatch?
快速搜索 Stack Overflow 以使用 C# 中的 IDispatch 出现 this post 说我想要的在 .NET 中是不可能的。
那么是否可以从 C# .NET 2.0 使用 COM?
问题是我想在 C#/.NET 中使用一种公认的设计模式。它涉及在进程外启动 Internet Explorer,并为其提供 HTML 内容,同时不使用临时文件。
一个被拒绝的设计想法是在 WinForm 上托管 Internet Explorer。
一种可接受的替代方法是启动系统注册的网络浏览器,使其显示 HTML,而不使用临时文件。
.NET 世界中继续使用 COM 对象的绊脚石。具体问题涉及在不需要 C# 4.0 的情况下执行对 IDispatch 的后期绑定调用。 (即在使用 .NET 2.0 时)
【问题讨论】:
-
出于好奇,总体目标是什么?您似乎想要启动 IE,然后显示传递的字符串的 HTML。是否需要您专门启动 IE,而不是 System.Windows.Forms.WebBrowser 控件?
-
您可以在进程外启动 System.Windows.Forms.WebBrowser 吗?
-
我想是可以做到的,但我自己还没有做到。如果我得到一些工作,我会回帖。
-
如果你成功了(不参考 PIA),你会得到一个湿漉漉的吻。
标签: c# com interop .net-2.0 idispatch