我正在做一些测试,以这种方式创建 HTMLDocument 的实例:
object[] pageText = { "<p>some text...</p>" };
var document = new HTMLDocumentClass();
var document2 = (IHTMLDocument2)document;
document2.write(pageText);
并且需要获得对 IMarkupServices 的引用。
这是我目前正在使用的代码:
Guid IID_IMarkupServices = new Guid("3050F4A0-98B5-11CF-BB82-00AA00BDCE0B");
IMarkupServices markupServices = GetService<IMarkupServices>(document, ID_IMarkupServices);
static Guid HTMLDocumentClassGuid = new Guid("25336920-03F9-11CF-8FD0-00AA00686F13");
private static T GetService<T>(IHTMLDocument2 document, Guid riid)
{
var serviceProvider = (IServiceProvider) document;
object service;
serviceProvider.QueryService(ref HTMLDocumentClassGuid, ref riid, out service);
return (T)service;
}
当我运行它(它托管在控制台应用程序中)时,会引发以下异常:
Unhandled Exception: System.InvalidCastException: Unable to cast COM object of type 'mshtml.HTMLDocumentClass' to interface type 'IServiceProvider'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{4C9A623C-FF69-3A3B-B592-43371C50DF88}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
at ConsoleApplication3.Program.GetService[T](IHTMLDocument2 document, Guid riid) in c:\users\admin\documents\visual studio 010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:line 35
at ConsoleApplication3.Program.Main(String[] args) in c:\users\admin\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:line 29
注意: 我要做的是对我用 mshtml 实现的一些对象进行单元测试。当我在 BHO(在 Internet Explorer 中)运行相同的代码时,它工作正常。
非常感谢
编辑:这是我最后用来让它工作的代码
我通过检查以下 WatiN 的实现使其工作:http ://www.java2s.com/Open-Source/CSharp/Web-Testing/WatiN/WatiN/Examples/MsHtmlBrowser/MsHtmlNativeBrowser.cs.htm 基于盛江有用的答案.
public class Program
{
[Guid("7FD52380-4E07-101B-AE2D-08002B2EC713")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPersistStreamInit
{
void GetClassID(out Guid pClassID);
int IsDirty();
void Load(System.Runtime.InteropServices.ComTypes.IStream pStm);
void Save(System.Runtime.InteropServices.ComTypes.IStream pStm, bool fClearDirty);
void GetSizeMax(out long pcbSize);
void InitNew();
}
[STAThread]
static void Main(string[] args)
{
var anHtmlDocument = new HTMLDocumentClass();
var aPersistStream = (WB.Program.IPersistStreamInit)anHtmlDocument;
aPersistStream.InitNew();
var anHtmlDocument2 = (IHTMLDocument2)anHtmlDocument;
anHtmlDocument2.write(new object[] { "test <b> foo </b>" });
anHtmlDocument2.close();
while (anHtmlDocument.readyState != "complete")
{
//This is also a important part, without this DoEvents() appz hangs on to the “loading”
Application.DoEvents();
}
var aMarkupService = (IMarkupServices)anHtmlDocument;
IMarkupPointer aPointer;
aMarkupService.CreateMarkupPointer(out aPointer);
var anHtmlBody = (IHTMLBodyElement)anHtmlDocument.body;
var aSelection = anHtmlBody.createTextRange();
aSelection.findText("foo", 0, 0);
}
}